The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(kanban): trim turn-recovery suite per review (1,136 -> 728 lines)
Evgeny Mettslerd50e8ef279c4
diff --git a/tests/agent/test_kanban_turn_recovery.py b/tests/agent/test_kanban_turn_recovery.pyindex e46763e3699..7ba15b897f1 100644--- a/tests/agent/test_kanban_turn_recovery.py+++ b/tests/agent/test_kanban_turn_recovery.py@@ -1,12 +1,13 @@"""Tests for kanban worker in-place turn recovery and the shared exit policy.-Covers the retry-authority rules (positive and typed: retryable failed turns-only; interrupts and durable terminal settlements are never retried), the live-run/claim proof taken before every attempt, the backoff schedule, the-continuation nudge contract, the single exit-code decision point shared by the-``chat -q`` and quiet ``-Q`` one-shot paths, and the call-site wiring in-``cli.py`` driven through ``cli.main`` (the settled-outcome hook the ``-q``-route reads, ``cli_chat_turn_mixin.py::_last_turn_result``, is main's own).+Unit contracts first (retry authority, the live run/claim proof, the recovery+loop), then call-site behaviour parametrized over the driver — production+``chat -q`` and quiet ``-Q`` — so each behaviour is stated once, then the+goal-mode veto as one table.++The exit mapping itself is main's ``cli._single_query_exit_code`` (pinned by+``tests/hermes_cli/test_single_query_exit_contract.py``); only the stripped+worker predicate this PR adds to it is pinned here."""from __future__ import annotations@@ -30,10 +31,7 @@ from agent.kanban_turn_recovery import (should_recover_turn,worker_claim_is_live,)-from hermes_cli.kanban_db import (- KANBAN_RATE_LIMIT_EXIT_CODE,- KANBAN_TERMINAL_PROVIDER_EXIT_CODE,-)+from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODEKANBAN_ENV = ("HERMES_KANBAN_TASK",@@ -44,6 +42,12 @@ KANBAN_ENV = ("HERMES_KANBAN_BOARD",)+#: The two one-shot routes sharing the exit decision: production ``chat -q`` and quiet ``-Q``.+DRIVERS = ("chat", "quiet")++#: Any "live" lease for these tests (2100-01-01 UTC).+_FAR_FUTURE_EXPIRY = 4_102_444_800+@pytest.fixturedef clear_kanban_env(monkeypatch):@@ -52,23 +56,48 @@ def clear_kanban_env(monkeypatch):return monkeypatch+def _worker_env(monkeypatch, *, task="t_probe", goal_mode=False, recovery=None):+ """The environment a dispatcher-spawned worker sees (goal mode is its flag)."""+ monkeypatch.setenv("HERMES_KANBAN_TASK", task)+ monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)+ if goal_mode:+ monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")+ if recovery is not None:+ monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", str(recovery))++def _failed(*, retryable: bool = True, reason: str = "timeout",error: str = "peer closed connection") -> dict:- return {- "failed": True,- "failure_retryable": retryable,- "failure_reason": reason,- "error": error,- "final_response": f"API call failed after 3 retries: {error}",- "completed": False,- "messages": [],- }+ return {"failed": True, "failure_retryable": retryable, "failure_reason": reason,+ "error": error, "final_response": f"API call failed after 3 retries: {error}",+ "completed": False, "messages": []}def _success() -> dict:return {"failed": False, "completed": True, "final_response": "done", "messages": []}+def _interrupted() -> dict:+ """``agent/turn_recovery.py::abort_turn_on_interrupt`` already persisted and cleared+ the interrupt — re-entering the model would resurrect cancelled work."""+ return {**_failed(), "interrupted": True, "api_calls": 4}+++def _settled() -> dict:+ """#87096: the bounded finalizer recorded a durable ``timed_out`` and released the+ claim while the result still reads ``completed=False`` — and here it ALSO carries a+ retryable failure stamp (the loop exhausted its provider retries, then hit the+ iteration cap). The settlement veto must win over the eligible-looking stamp."""+ return {**_failed(retryable=True), "turn_exit_reason": "max_iterations_reached(60/60)"}+++def _partial() -> dict:+ """An outcome, not retry authority: truncation repair belongs in the conversation+ loop (#89289)."""+ return {"partial": True, "completed": False, "final_response": "cut off",+ "error": "truncated", "messages": []}++# ── enablement / budget ──────────────────────────────────────────────@@ -83,12 +112,20 @@ def test_disabled_without_kanban_task(clear_kanban_env):assert calls == []-def test_env_zero_disables(clear_kanban_env):+def test_env_zero_disables_and_blank_ids_are_not_workers(clear_kanban_env):clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")clear_kanban_env.setenv("HERMES_KANBAN_TURN_RECOVERY", "0")assert kanban_turn_recovery_enabled() is Falseassert should_recover_turn(_failed(), attempt=0) is False+ clear_kanban_env.setenv("HERMES_KANBAN_TASK", " ")+ assert kanban_task_id() is None # whitespace-only is NOT a worker, anywhere+ assert kanban_turn_recovery_enabled() is False+ clear_kanban_env.delenv("HERMES_KANBAN_TURN_RECOVERY", raising=False)+ clear_kanban_env.setenv("HERMES_KANBAN_TASK", " t_probe ")+ assert kanban_task_id() == "t_probe" # padded ids are the same worker+ assert kanban_turn_recovery_enabled() is True+def test_max_attempts_parsing_and_clamp(clear_kanban_env):clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")@@ -111,16 +148,7 @@ def test_delay_schedule_repeats_last_entry():assert recovery_delay_seconds(0) == 15.0-def test_kanban_task_id_strips_and_rejects_blank(clear_kanban_env):- clear_kanban_env.setenv("HERMES_KANBAN_TASK", " ")- assert kanban_task_id() is None # whitespace-only is NOT a worker, anywhere- assert kanban_turn_recovery_enabled() is False- clear_kanban_env.setenv("HERMES_KANBAN_TASK", " t_probe ")- assert kanban_task_id() == "t_probe"- assert kanban_turn_recovery_enabled() is True---# ── retry authority: positive and typed ──────────────────────────────+# ── retry authority (the unit contract behind both drivers) ──────────def test_retryable_failed_turn_is_eligible(clear_kanban_env):@@ -130,109 +158,50 @@ def test_retryable_failed_turn_is_eligible(clear_kanban_env):assert should_recover_turn(_failed(reason="timeout"), attempt=3) is False-def test_not_retryable_is_not_recovered(clear_kanban_env):- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- assert should_recover_turn(_failed(retryable=False, reason="auth"), attempt=0) is False- assert should_recover_turn(_success(), attempt=0) is False- assert should_recover_turn(None, attempt=0) is False---def test_rate_limit_and_billing_are_left_to_the_dispatcher(clear_kanban_env):- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- assert should_recover_turn(_failed(reason="rate_limit"), attempt=0) is False- assert should_recover_turn(_failed(reason="billing"), attempt=0) is False---def test_upstream_rate_limit_is_a_dispatcher_quota_wall(clear_kanban_env):- """The aggregator's upstream 429 is the same quota-class wall as a direct 429:- not retried in place, and released as the neutral 75 for a worker (main's- ``_TRANSIENT_PROVIDER_REASONS``); a person's run books it as a plain 1."""- from cli import _single_query_exit_code-- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- assert should_recover_turn(_failed(reason="upstream_rate_limit"), attempt=0) is False- assert _single_query_exit_code(_failed(reason="upstream_rate_limit")) == 75- clear_kanban_env.delenv("HERMES_KANBAN_TASK", raising=False)- assert _single_query_exit_code(_failed(reason="upstream_rate_limit")) == 1---def test_interrupt_is_never_retry_authority(clear_kanban_env):- """``agent/turn_recovery.py::abort_turn_on_interrupt`` already persisted and- cleared the interrupt — re-entering the model would resurrect cancelled work."""- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- interrupted = {- "final_response": "interrupted", "messages": [], "api_calls": 4,- "completed": False, "interrupted": True,- "failed": True, "failure_retryable": True, "failure_reason": "timeout",- }- assert should_recover_turn(interrupted, attempt=0) is False---def test_terminal_settlement_is_never_retry_authority(clear_kanban_env):- """#87096: the bounded kanban finalizer records ``outcome="timed_out"`` and- releases the claim while the result still reads ``completed=False`` — retrying- would continue work after this exact run was terminalized."""- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- settled = {- "final_response": "budget exhausted", "messages": [], "api_calls": 60,- "completed": False, "failed": False,- "turn_exit_reason": "max_iterations_reached(60/60)",- }- assert should_recover_turn(settled, attempt=0) is False- # The sharp combination: the turn ALSO carries a retryable failure verdict (the- # loop exhausted its provider retries and then hit the iteration cap, so the- # finalizer terminalized the run). The settlement veto must win over the- # otherwise-eligible failure stamp.- sharp = {**_failed(retryable=True), "turn_exit_reason": "max_iterations_reached(60/60)"}- assert should_recover_turn(sharp, attempt=0) is False- # …and the exit policy still books it honestly rather than as a silent rc=0- # (no failure_reason on a settled turn → not transient → honest 1).- from cli import _single_query_exit_code-- assert _single_query_exit_code(settled) == 1---def test_incomplete_turn_is_not_retry_authority(clear_kanban_env):- """``partial`` / ``completed=False`` describe an outcome; they are not retry- authority (truncation repair belongs inside the conversation loop, #89289)."""+ "result",+ [+ pytest.param(_failed(retryable=False, reason="auth"), id="not-retryable"),+ pytest.param(_success(), id="success"),+ pytest.param(None, id="nothing-settled"),+ pytest.param(_failed(reason="rate_limit"), id="quota-wall"),+ pytest.param(_failed(reason="billing"), id="billing-wall"),+ pytest.param(_failed(reason="upstream_rate_limit"), id="upstream-quota-wall"),+ pytest.param(_interrupted(), id="interrupt"),+ pytest.param(_settled(), id="terminal-settlement"),+ pytest.param(_partial(), id="unfinished-nonfailed"),+ pytest.param({"completed": False, "final_response": "x"}, id="completed-false"),+ ],+)+def test_should_recover_turn_refuses(result, clear_kanban_env):+ """Nothing but a retryable failed turn is retry authority. The aggregator's upstream+ 429 is the same quota-class wall as a direct one — the dispatcher owns the cooldown."""clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- partial = {"partial": True, "completed": False, "final_response": "cut off",- "error": "truncated", "messages": []}- assert should_recover_turn(partial, attempt=0) is False- assert should_recover_turn({"completed": False, "final_response": "x"}, attempt=0) is False+ assert should_recover_turn(result, attempt=0) is False-# ── live run/claim proof ─────────────────────────────────────────────---#: Any "live" lease for these tests (2100-01-01 UTC).-_FAR_FUTURE_EXPIRY = 4_102_444_800+# ── live run/claim proof (the adversarial boundaries) ────────────────def _make_board(tmp_path, *, status="running", task_pid=None, run_id=1, lock="lk",run_ended=None, run_pid=None, task_expires=_FAR_FUTURE_EXPIRY,run_expires=_FAR_FUTURE_EXPIRY):- """A synthetic board whose task carries a LIVE, unexpired task+run lease by- default (current-main dispatcher shape: ``claim_task`` sets ``claim_expires``- on both rows and ``heartbeat_claim`` mirrors the extension)."""+ """A synthetic board whose task carries a LIVE, unexpired task+run lease by default+ (current-main dispatcher shape: ``claim_task`` sets ``claim_expires`` on both rows+ and ``heartbeat_claim`` mirrors the extension)."""db = tmp_path / "kanban.db"conn = sqlite3.connect(db)- conn.execute(- "CREATE TABLE tasks (id TEXT PRIMARY KEY, status TEXT, worker_pid INTEGER, "- "current_run_id INTEGER, claim_lock TEXT, claim_expires INTEGER)"- )- conn.execute(- "CREATE TABLE task_runs (id INTEGER PRIMARY KEY, ended_at INTEGER, "- "worker_pid INTEGER, claim_expires INTEGER)"- )- conn.execute(- "INSERT INTO tasks VALUES (?, ?, ?, ?, ?, ?)",- ("t_live", status, task_pid, run_id, lock, task_expires),+ conn.executescript(+ "CREATE TABLE tasks (id TEXT PRIMARY KEY, status TEXT, worker_pid INTEGER,"+ " current_run_id INTEGER, claim_lock TEXT, claim_expires INTEGER);"+ "CREATE TABLE task_runs (id INTEGER PRIMARY KEY, ended_at INTEGER,"+ " worker_pid INTEGER, claim_expires INTEGER);")+ conn.execute("INSERT INTO tasks VALUES (?, ?, ?, ?, ?, ?)",+ ("t_live", status, task_pid, run_id, lock, task_expires))if run_id is not None:- conn.execute(- "INSERT INTO task_runs VALUES (?, ?, ?, ?)", (run_id, run_ended, run_pid, run_expires)- )+ conn.execute("INSERT INTO task_runs VALUES (?, ?, ?, ?)",+ (run_id, run_ended, run_pid, run_expires))conn.commit()conn.close()return db@@ -246,36 +215,31 @@ def _pin_carrier(monkeypatch, db, *, task="t_live", run_id="1", lock="lk"):monkeypatch.setenv("HERMES_KANBAN_CLAIM_LOCK", lock)-def test_claim_is_live_when_this_worker_still_owns_the_run(clear_kanban_env, tmp_path):- db = _make_board(tmp_path, task_pid=os.getpid(), run_id=7, lock="lk", run_pid=os.getpid())- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_live")- clear_kanban_env.setenv("HERMES_KANBAN_DB", str(db))- clear_kanban_env.setenv("HERMES_KANBAN_RUN_ID", "7")- clear_kanban_env.setenv("HERMES_KANBAN_CLAIM_LOCK", "lk")- assert worker_claim_is_live() is True--@pytest.mark.parametrize("overrides",[- {"status": "ready"}, # task was released back to the board- {"task_pid": 999_999_999}, # another process owns the claim- {"run_ended": 12345}, # run already closed (settled)- {"run_pid": 999_999_999}, # run handed to another pid- {"run_id": None}, # no live run pointer- {"run_id": 2}, # board moved to a different run id- {"lock": "other-lock"}, # claim lock no longer ours- {"task_expires": 1}, # task lease has EXPIRED- {"run_expires": 1}, # run lease has EXPIRED (heartbeat mirror)- {"task_expires": None}, # no provable task lease — NULL is not "unbounded"- {"run_expires": None}, # no provable run lease+ pytest.param({}, id="owned-live"),+ pytest.param({"status": "ready"}, id="released-to-the-board"),+ pytest.param({"task_pid": 999_999_999}, id="other-process-owns-the-claim"),+ pytest.param({"run_ended": 12345}, id="run-already-closed"),+ pytest.param({"run_pid": 999_999_999}, id="run-handed-to-another-pid"),+ pytest.param({"run_id": None}, id="no-live-run-pointer"),+ pytest.param({"run_id": 2}, id="board-moved-to-another-run"),+ pytest.param({"lock": "other-lock"}, id="claim-lock-no-longer-ours"),+ pytest.param({"task_expires": 1}, id="task-lease-expired"),+ pytest.param({"run_expires": 1}, id="run-lease-expired"),+ pytest.param({"task_expires": None}, id="null-task-lease-is-not-unbounded"),+ pytest.param({"run_expires": None}, id="null-run-lease-is-not-unbounded"),],)-def test_claim_is_not_live_when_ownership_is_broken(clear_kanban_env, tmp_path, overrides):+def test_claim_ownership_matrix(clear_kanban_env, tmp_path, overrides):+ """``worker_claim_is_live`` authorises model re-entry, so every broken coordinate must+ deny it — a NULL lease is not "unbounded", and the pinned carrier itself stays intact+ (the denial has to come from the board rows, not from a missing pin)."""board = {"task_pid": os.getpid(), "run_pid": os.getpid(), **overrides}db = _make_board(tmp_path, **board)- _pin_carrier(clear_kanban_env, db) # the pinned carrier itself is intact- assert worker_claim_is_live() is False+ _pin_carrier(clear_kanban_env, db)+ assert worker_claim_is_live() is (overrides == {})def test_claim_check_fails_closed_without_a_board(clear_kanban_env, tmp_path):@@ -289,31 +253,26 @@ def test_claim_check_fails_closed_without_a_board(clear_kanban_env, tmp_path):def test_missing_pinned_carrier_fails_closed(clear_kanban_env, tmp_path):- """Round-2 P1: the dispatcher pins DB + run id + claim lock at spawn. Any- MISSING coordinate means there is no exact authority carrier to re-prove —- the proof fails closed instead of widening to ambient board state or- skipping comparisons."""+ """Round-2 P1: the dispatcher pins DB + run id + claim lock at spawn. Any MISSING+ coordinate means there is no exact authority carrier to re-prove — the proof fails+ closed instead of widening to ambient board state or skipping comparisons."""db = _make_board(tmp_path) # a live board with a live lease_pin_carrier(clear_kanban_env, db)assert worker_claim_is_live() is True # sanity: the full carrier proves live- clear_kanban_env.delenv("HERMES_KANBAN_DB", raising=False)- assert worker_claim_is_live() is False # missing DB pin- clear_kanban_env.setenv("HERMES_KANBAN_DB", str(db))- clear_kanban_env.delenv("HERMES_KANBAN_RUN_ID", raising=False)- assert worker_claim_is_live() is False # missing run-id pin- clear_kanban_env.setenv("HERMES_KANBAN_RUN_ID", "1")- clear_kanban_env.delenv("HERMES_KANBAN_CLAIM_LOCK", raising=False)- assert worker_claim_is_live() is False # missing claim-lock pin+ for missing, value in (("HERMES_KANBAN_DB", str(db)), ("HERMES_KANBAN_RUN_ID", "1"),+ ("HERMES_KANBAN_CLAIM_LOCK", "lk")):+ clear_kanban_env.delenv(missing, raising=False)+ assert worker_claim_is_live() is False, missing # a missing pin denies+ clear_kanban_env.setenv(missing, value)def test_missing_db_pin_never_resolves_an_ambient_board(tmp_path, monkeypatch):- """Round-2 P1: the old code reconstructed the board from- ``HERMES_KANBAN_BOARD`` / the default when the pin was absent — the proof- could silently move to whatever board is ambient NOW. With the pin gone the- canonical resolver must not be consulted at all, even when it would return a- fully live board whose row matches this worker (built with the real board- API so this is not a strawman)."""+ """Round-2 P1: the old code reconstructed the board from ``HERMES_KANBAN_BOARD`` /+ the default when the pin was absent — the proof could silently move to whatever board+ is ambient NOW. With the pin gone the canonical resolver must not be consulted at all,+ even when it would return a fully live board whose row matches this worker (built with+ the real board API, so this is not a strawman)."""from hermes_cli import kanban_db as kbfrom hermes_cli import kanban_db_connect as kbc@@ -324,8 +283,7 @@ def test_missing_db_pin_never_resolves_an_ambient_board(tmp_path, monkeypatch):kb.init_db()with kbc.connect() as conn:task_id = kb.create_task(conn, title="ambient live task")- claimed = kb.claim_task(conn, task_id, claimer="lk", ttl_seconds=3600)- assert claimed is not None # running, lock+run pointer+unexpired TTL set+ assert kb.claim_task(conn, task_id, claimer="lk", ttl_seconds=3600) is not Nonemonkeypatch.delenv("HERMES_KANBAN_DB", raising=False)monkeypatch.delenv("HERMES_KANBAN_RUN_ID", raising=False)monkeypatch.delenv("HERMES_KANBAN_CLAIM_LOCK", raising=False)@@ -345,11 +303,13 @@ def test_missing_db_pin_never_resolves_an_ambient_board(tmp_path, monkeypatch):assert consulted == [] # no ambient resolution was attempted-def test_lease_expired_during_the_backoff_blocks_model_reentry(clear_kanban_env, tmp_path, monkeypatch):- """Round-2 P1 (the reviewer's exact race): failure near TTL expiry → the- pre-backoff proof passes → the 15/45/90s sleep crosses expiry → the- post-backoff re-proof must FAIL on the unexpired-lease check even though- status/run-id/lock/pid/ended_at are all unchanged. No model turn is made."""+def test_lease_expired_during_the_backoff_blocks_model_reentry(+ clear_kanban_env, tmp_path, monkeypatch+):+ """Round-2 P1 (the reviewer's exact race): failure near TTL expiry → the pre-backoff+ proof passes → the 15/45/90s sleep crosses expiry → the post-backoff re-proof must FAIL+ on the unexpired-lease check even though status/run-id/lock/pid/ended_at are all+ unchanged. No model turn is made."""import agent.kanban_turn_recovery as recdb = _make_board(tmp_path, task_expires=1_600, run_expires=1_600)@@ -375,32 +335,34 @@ def _loop_ok(result=None):return (lambda: True) if result is None else result-def test_recovery_loop_retries_until_success(clear_kanban_env):+def test_recovery_loop_retries_until_success_and_reports(clear_kanban_env):clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")latest = {"r": _failed()}turns: list[str] = []delays: list[float] = []+ emitted: list[str] = []def turn_fn(nudge: str) -> None:turns.append(nudge)latest["r"] = _success() # provider recoveredattempts = recover_failed_kanban_turns(- turn_fn, lambda: latest["r"], sleep_fn=delays.append, emit=lambda m: None,+ turn_fn, lambda: latest["r"], sleep_fn=delays.append, emit=emitted.append,claim_check=_loop_ok(),)assert attempts == 1assert delays == [15.0]assert "Do NOT start over" in turns[0]assert "t_probe" in turns[0]+ assert len(emitted) == 1+ assert "[kanban]" in emitted[0] and "attempt 1/3" in emitted[0]def test_recovery_loop_bounded_when_result_never_changes(clear_kanban_env):clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- turns: list[str] = []delays: list[float] = []attempts = recover_failed_kanban_turns(- lambda nudge: turns.append(nudge),+ lambda nudge: None,lambda: _failed(), # stuck result: must NOT loop foreversleep_fn=delays.append, emit=lambda m: None, claim_check=_loop_ok(),)@@ -408,67 +370,41 @@ def test_recovery_loop_bounded_when_result_never_changes(clear_kanban_env):assert delays == [15.0, 45.0, 90.0]-def test_recovery_loop_checks_the_claim_before_every_attempt(clear_kanban_env):- """The live run/claim proof is re-taken for EACH attempt. A run lost while we- were backing off (the dispatcher can reclaim during the 15/45/90s sleep) must- stop the loop WITHOUT re-entering the model — round-5 finding F1."""+def test_recovery_loop_order_is_check_sleep_check_turn(clear_kanban_env):+ """Round-5 finding F1, both halves in one pass: the proof is taken BEFORE the backoff+ and re-taken immediately before model re-entry (check → sleep → check → turn), so a run+ lost during the 15/45/90s sleep stops the loop WITHOUT re-entering the model."""clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")clear_kanban_env.setenv("HERMES_KANBAN_TURN_RECOVERY", "3")- checks: list[int] = []- turns: list[str] = []- emitted: list[str] = []-- def claim_check() -> bool:- checks.append(len(checks) + 1)- return len(checks) == 1 # first proof holds; the run is lost during the backoff-- attempts = recover_failed_kanban_turns(- lambda nudge: turns.append(nudge), lambda: _failed(),- sleep_fn=lambda s: None, emit=emitted.append, claim_check=claim_check,- )- assert checks == [1, 2] # pre-backoff proof + the pre-entry re-proof- assert attempts == 1 # the attempt was authorised …- assert len(turns) == 0 # … but the run was gone before re-entry: no model turn- assert "no longer holds a live run/claim" in emitted[-1]---def test_recovery_loop_rechecks_the_claim_after_the_backoff(clear_kanban_env):- """Order pin: check -> sleep -> check -> turn. The re-proof sits immediately- before model re-entry, not only before the backoff (round-5 finding F1)."""- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")events: list[str] = []latest = {"r": _failed()}+ proofs = {"n": 0}def claim_check() -> bool:+ proofs["n"] += 1events.append("check")- return True-- def sleeper(_seconds: float) -> None:- events.append("sleep")+ return proofs["n"] == 1 # first proof holds; the run is lost during the backoffdef turn_fn(nudge: str) -> None:- events.append("turn")+ events.append("turn") # a model entry: must NOT happen on the denied pathlatest["r"] = _success()attempts = recover_failed_kanban_turns(- turn_fn, lambda: latest["r"], sleep_fn=sleeper, emit=lambda m: None,- claim_check=claim_check,+ turn_fn, lambda: latest["r"], sleep_fn=lambda s: events.append("sleep"),+ emit=lambda m: None, claim_check=claim_check,)- assert attempts == 1- assert events == ["check", "sleep", "check", "turn"]-+ assert events == ["check", "sleep", "check"] # the lost run vetoed re-entry+ assert attempts == 1 # the attempt was authorised …-def test_recovery_emit_receives_status_line(clear_kanban_env):- clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")- emitted: list[str] = []- latest = {"r": _failed()}- recover_failed_kanban_turns(- lambda nudge: latest.update(r=_success()), lambda: latest["r"],- sleep_fn=lambda s: None, emit=emitted.append, claim_check=_loop_ok(),+ # …and with the proof intact, the happy path is the full check → sleep → check → turn.+ events.clear()+ latest["r"] = _failed()+ attempts = recover_failed_kanban_turns(+ turn_fn, lambda: latest["r"], sleep_fn=lambda s: events.append("sleep"),+ emit=lambda m: None, claim_check=lambda: (events.append("check"), True)[1],)- assert len(emitted) == 1- assert "[kanban]" in emitted[0]- assert "attempt 1/3" in emitted[0]+ assert attempts == 1+ assert events == ["check", "sleep", "check", "turn"]def test_nudge_terminal_contract(clear_kanban_env):@@ -482,655 +418,310 @@ def test_nudge_terminal_contract(clear_kanban_env):assert "peer closed connection" in nudge-# ── shared exit-code policy ──────────────────────────────────────────+# ── what this PR adds to the shared exit mapping ─────────────────────-def test_single_query_exit_code_policy(monkeypatch):- """The shared exit mapping is main's ``cli._single_query_exit_code`` — this PR- composes with it (stripped worker predicate) and must not fork it. Pins the- composed contract as main defines it today: transient provider walls release a- worker as the neutral 75, terminal provider verdicts park it as EX_CONFIG 78,- other failures and unfinished turns are honest 1s, interrupts are 130,- success 0."""+def test_exit_mapping_composes_with_the_stripped_worker_predicate(monkeypatch):+ """``cli._single_query_exit_code`` is main's (its own contract test pins the mapping);+ this PR's contribution is that it asks ``kanban_task_id()`` whether this is a worker.+ Pin exactly that: surrounding whitespace must not decide worker-ness, or a+ bare-whitespace id would hand a quota wall the neutral 75."""from cli import _single_query_exit_code- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- assert _single_query_exit_code(_success()) == 0- # transient provider walls: neutral 75 for a worker — quota walls and the- # broader transient set (a storm that outlasts in-place recovery is released,- # not counted against the breaker)- for reason in ("rate_limit", "billing", "upstream_rate_limit", "timeout", "overloaded"):- assert _single_query_exit_code(_failed(reason=reason)) == KANBAN_RATE_LIMIT_EXIT_CODE- # terminal provider verdicts (revoked credential, model gone, WAF block) are- # main's EX_CONFIG: the dispatcher parks the card after ONE spawn instead of- # re-spawning into the same wall- for reason in ("auth", "auth_permanent", "model_not_found", "ssl_cert_verification",- "upstream_blocked"):- assert _single_query_exit_code(_failed(reason=reason)) == KANBAN_TERMINAL_PROVIDER_EXIT_CODE- # a non-transient, non-terminal worker failure is an honest 1- assert _single_query_exit_code(_failed(reason="some_unknown_reason")) == 1- # unfinished / nothing settled: honest 1 — never a silent rc=0- assert _single_query_exit_code(None) == 1- assert _single_query_exit_code({"partial": True, "completed": False}) == 1- # explicit cancellation: 130 — never retried, never continued- assert _single_query_exit_code({**_failed(), "interrupted": True}) == 130-- # a person's run: no neutral release — a wall is just a failure- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- assert _single_query_exit_code(_success()) == 0+ monkeypatch.setenv("HERMES_KANBAN_TASK", " ")assert _single_query_exit_code(_failed(reason="rate_limit")) == 1- assert _single_query_exit_code(_failed(reason="timeout")) == 1- assert _single_query_exit_code(None) == 1---# ── call-site behaviour (drive cli.main with a FakeCLI) ──────────────---def _install_fake_cli(monkeypatch, chat_script, calls):- """Mirror tests/hermes_cli/test_single_query_session_finalize.py's FakeCLI harness."""- import cli as cli_mod-- class _Console:- def print(self, *a, **k):- calls.append("query-label")-- class FakeCLI:- def __init__(self, **_kwargs):- self.console = _Console()- self.session_id = "single-query-session"- self.agent = SimpleNamespace(session_id="single-query-session", platform="cli")-- def _claim_active_session(self, surface, *, stderr=False):- return True+ monkeypatch.setenv("HERMES_KANBAN_TASK", " t_probe ")+ assert _single_query_exit_code(_failed(reason="rate_limit")) == KANBAN_RATE_LIMIT_EXIT_CODE- def _show_security_advisories(self):- pass- def chat(self, query, images=None):- calls.append(("chat", query))- result = chat_script() if callable(chat_script) else chat_script.pop(0)- self._last_turn_result = result- # Mirror production: chat() returns the settled turn's rendered response —- # for a failed turn that IS the provider error text.- return result.get("final_response", "") if isinstance(result, dict) else ""+# ── call-site behaviour: one harness for both drivers ────────────────- def _print_exit_summary(self, clear_screen=True):- calls.append("summary")- monkeypatch.setattr(cli_mod, "HermesCLI", FakeCLI)- monkeypatch.setattr(cli_mod.atexit, "register", lambda *a, **k: None)- monkeypatch.setattr(cli_mod, "_finalize_single_query", lambda fake_cli: None)- monkeypatch.setattr(cli_mod, "_collect_query_images", lambda q, img: (q, []))- monkeypatch.setattr(cli_mod, "_collect_kanban_task_images", lambda imgs: [])- return cli_mod+def cli_harness(monkeypatch):+ """Drive the real ``cli.main`` on either one-shot route through one fake CLI.++ ``script`` is the sequence of settled turn results — or a callable returning one on+ every call. Returns ``(cli_mod, entered, ui)``, where ``entered`` records the user+ message of every model entry, so a test can prove how many turns were taken and what+ the recovery nudge carried, and ``ui`` records non-turn route marks (the exit summary).+ """++ def _install(driver, script):+ import cli as cli_mod++ entered: list[str] = []+ ui: list[str] = []+ seen = {"n": 0}++ class _Feed:+ """Superset of both routes' surfaces: ``chat -q`` drives ``chat()``, the quiet+ route drives ``agent.run_conversation``."""++ def __init__(self, **_kwargs):+ self.console = SimpleNamespace(print=lambda *a, **k: None)+ self.provider = "test-provider"+ self.model = "test-model"+ self.session_id = "single-query-session"+ self.conversation_history = []+ self._active_agent_route_signature = "same-route"+ self.agent = SimpleNamespace(+ session_id="single-query-session", platform="cli", quiet_mode=False,+ suppress_status_output=False, stream_delta_callback=object(),+ tool_gen_callback=object(), run_conversation=self._run_conversation,+ )++ def _next(self):+ result = script() if callable(script) else script[seen["n"]]+ seen["n"] += 1+ return result++ def _run_conversation(self, *, user_message, conversation_history):+ entered.append(user_message)+ return self._next()++ def chat(self, query, images=None):+ entered.append(query)+ result = self._next()+ self._last_turn_result = result+ # Mirror production: chat() returns the settled turn's rendered response —+ # for a failed turn that IS the provider error text.+ return result.get("final_response", "") if isinstance(result, dict) else ""++ # route plumbing+ def _claim_active_session(self, surface, *, stderr=False):+ return True++ def _ensure_runtime_credentials(self):+ return True++ def _resolve_turn_agent_config(self, effective_query):+ return {"signature": "same-route", "model": None, "runtime": None,+ "request_overrides": None}++ def _init_agent(self, **kwargs):+ return True++ def _show_security_advisories(self):+ pass++ def _print_exit_summary(self, clear_screen=True):+ ui.append("summary")++ monkeypatch.setattr(cli_mod, "HermesCLI", _Feed)+ monkeypatch.setattr(cli_mod.atexit, "register", lambda *a, **k: None)+ monkeypatch.setattr(cli_mod, "_finalize_single_query", lambda fake_cli: None)+ monkeypatch.setattr(cli_mod, "_collect_query_images", lambda q, img: (q, []))+ monkeypatch.setattr(cli_mod, "_collect_kanban_task_images", lambda imgs: [])+ return cli_mod, entered, ui++ return _install+++def _drive(cli_mod, driver) -> int:+ """Run one one-shot query on ``driver`` and return the exit code it raised."""+ kwargs: dict = {"query": "hello", "toolsets": "terminal"}+ if driver == "chat":+ kwargs.update(quiet=False, oneshot=True)+ else:+ kwargs.update(quiet=True)+ with pytest.raises(SystemExit) as exc_info:+ cli_mod.main(**kwargs)+ return exc_info.value.code@pytest.fixturedef live_claim(monkeypatch):- """The board proof is a separate contract (unit-tested above); call-site tests- run against a worker that owns its run, unless a test overrides it."""+ """The board proof is a separate contract (unit-tested above); the call-site tests run+ against a worker that owns its run unless the test overrides it."""import agent.kanban_turn_recovery as recmonkeypatch.setattr(rec, "worker_claim_is_live", lambda: True)return rec-def _chats(calls):- return [c for c in calls if isinstance(c, tuple) and c[0] == "chat"]---def test_non_quiet_kanban_recovers_in_place(monkeypatch, live_claim):- import agent.kanban_turn_recovery as rec-- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "2")- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed(), _success()], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 0 # settled successfully- chats = _chats(calls)- assert len(chats) == 2- assert "Do NOT start over" in chats[1][1]- assert "t_probe" in chats[1][1]---def test_non_quiet_kanban_exits_nonzero_after_budget(monkeypatch, live_claim):- import agent.kanban_turn_recovery as rec-- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "1")- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, _failed, calls) # never recovers-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 75 # exhausted transient wall: released, not counted- assert len(_chats(calls)) == 2 # original + one recovery attempt--[email protected]("reason", ["rate_limit", "billing", "upstream_rate_limit"])-def test_non_quiet_rate_limit_keeps_the_neutral_exit_code(monkeypatch, live_claim, reason):- """#48000-class boundary: the production ``chat -q`` route must hand a quota- wall (including the aggregator's upstream 429) to the dispatcher as the- neutral EX_TEMPFAIL code, not a counted crash."""- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed(reason=reason)], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 75- assert len(_chats(calls)) == 1 # declined in place: the dispatcher owns the cooldown---def test_non_quiet_interrupted_turn_is_not_retried(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- interrupted = {**_failed(), "interrupted": True}- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [interrupted], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 130 # main's interrupt exit: never retried, never continued- assert len(_chats(calls)) == 1---def test_non_quiet_terminal_settlement_is_not_retried(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- settled = {**_failed(retryable=True),- "turn_exit_reason": "max_iterations_reached(60/60)"}- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [settled], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- # never retried, never continued; the transient stamp books the neutral 75 —- # the #87096 settlement already recorded the durable timed_out outcome.- assert exc_info.value.code == 75- assert len(_chats(calls)) == 1---def test_non_quiet_partial_is_not_retried(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- partial = {"partial": True, "completed": False, "final_response": "cut off",- "error": "truncated", "messages": []}- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [partial], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(_chats(calls)) == 1---def test_non_quiet_skips_recovery_without_a_live_claim(monkeypatch, capsys):- import agent.kanban_turn_recovery as rec-- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setattr(rec, "worker_claim_is_live", lambda: False)- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed()], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 75 # denial still exits non-zero; transient → release- assert len(_chats(calls)) == 1- assert "no longer holds a live run/claim" in capsys.readouterr().err---def test_non_quiet_kanban_no_settled_outcome_exits_nonzero(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [None], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(_chats(calls)) == 1---def test_non_kanban_failed_run_exits_one_without_recovery(monkeypatch, live_claim):- """No HERMES_KANBAN_TASK: no in-place recovery; main's shared exit contract- books a failed run as 1 (the non-quiet tail now exits unconditionally)."""- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed()], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(_chats(calls)) == 1 # no recovery outside kanban workers- assert "summary" in calls---def test_whitespace_task_id_is_not_a_worker_anywhere(monkeypatch, live_claim):- """A whitespace-only HERMES_KANBAN_TASK is not a worker: the exit mapping's- stripped predicate must not hand a quota wall the neutral 75 (raw env- truthiness would)."""- monkeypatch.setenv("HERMES_KANBAN_TASK", " ")- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed(reason="rate_limit")], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")-- assert exc_info.value.code == 1 # not 75: not a worker, not neutralized- assert len(_chats(calls)) == 1---def _install_quiet_fake_cli(monkeypatch, run_conversation):- """Quiet (-Q) harness: minimal HermesCLI whose agent runs the given function."""- import cli as cli_mod-- class FakeCLI:- def __init__(self, **_kwargs):- self.provider = "test-provider"- self.model = "test-model"- self.session_id = "quiet-session"- self.conversation_history = []- self._active_agent_route_signature = "same-route"- self.agent = SimpleNamespace(- session_id="quiet-session", platform="cli", quiet_mode=False,- suppress_status_output=False, stream_delta_callback=object(),- tool_gen_callback=object(), run_conversation=run_conversation,- )-- def _claim_active_session(self, surface, *, stderr=False):- return True-- def _ensure_runtime_credentials(self):- return True-- def _resolve_turn_agent_config(self, effective_query):- return {"signature": "same-route", "model": None, "runtime": None, "request_overrides": None}-- def _init_agent(self, **kwargs):- return True-- monkeypatch.setattr(cli_mod, "HermesCLI", FakeCLI)- monkeypatch.setattr(cli_mod.atexit, "register", lambda *a, **k: None)- monkeypatch.setattr(cli_mod, "_finalize_single_query", lambda fake_cli: None)- monkeypatch.setattr(cli_mod, "_collect_kanban_task_images", lambda imgs: [])- return cli_mod---def test_quiet_kanban_recovers_in_place(monkeypatch, live_claim):- import agent.kanban_turn_recovery as rec-- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "2")- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed() if len(runs) == 1 else _success()-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 0- assert len(runs) == 2- assert "Do NOT start over" in runs[1]---def test_quiet_rate_limit_keeps_the_neutral_exit_code(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed(reason="billing")-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 75- assert len(runs) == 1---def test_quiet_partial_exits_nonzero_without_retrying(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return {"partial": True, "completed": False, "final_response": "cut off",- "error": "truncated"}-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(runs) == 1---def test_quiet_kanban_no_settled_outcome_exits_nonzero(monkeypatch, live_claim):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return None-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(runs) == 1---def test_quiet_non_kanban_no_settled_outcome_is_booked_honestly(monkeypatch, live_claim):- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return None-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 1 # main's shared contract: unsettled is 1 for every caller- assert len(runs) == 1---# ── goal-mode composition (round-3): a recovery refusal stops ALL model entry ──--@pytest.fixturedef goal_spy(monkeypatch):- """Spy on the goal continuation loop at the cli-module seam. The goal loop- itself is pre-existing (its status check sees only run identity, not the- claim lease); the invariant under test here is the CALL-SITE gate."""+ """Spy on BOTH goal continuation loops at the cli-module seam. The loops are+ pre-existing (their status check sees only run identity, not the claim lease); the+ invariant under test is the call-site veto this PR adds."""import cli as cli_modcalls: list = []- monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_q", lambda c, resp: calls.append(resp))+ monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_q",+ lambda c, resp: calls.append((resp, "quiet")))+ monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_chat",+ lambda c, resp: calls.append((resp, "chat")))return calls-def _quiet_goal_env(monkeypatch):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")---def test_goal_mode_does_not_continue_after_recovery_denial(monkeypatch, capsys, goal_spy):- """Round-3 P1: with goal mode ON, a DENIED recovery (claim lost) must reach- the shared exit path without goal continuation — the goal loop's status- check sees only run identity, so continuing would re-enter the model under- an authority this process can no longer prove."""[email protected]("driver", DRIVERS)+def test_recovers_in_place(driver, cli_harness, live_claim, monkeypatch):import agent.kanban_turn_recovery as rec- _quiet_goal_env(monkeypatch)- monkeypatch.setattr(rec, "worker_claim_is_live", lambda: False) # recovery denied- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed()-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 75 # timeout stamp → transient release; gate still vetoes- assert len(runs) == 1 # the failed turn only: no recovery nudge, and- assert goal_spy == [] # NO goal continuation after the denial- assert "no longer holds a live run/claim" in capsys.readouterr().err---def test_goal_mode_does_not_continue_when_the_lease_expires_during_the_backoff(- clear_kanban_env, tmp_path, monkeypatch, goal_spy-):- """Round-3 P1, the reviewer's exact reproduced fixture, end to end through- ``cli.main``: both leases at 1600, pre-backoff proof at 1000 passes, the- backoff crosses to 1700, the re-proof refuses — and goal mode (which sees a- still-running identity-only status) must NOT start another model turn."""- import agent.kanban_turn_recovery as rec-- db = _make_board(tmp_path, task_expires=1_600, run_expires=1_600)- _pin_carrier(clear_kanban_env, db, run_id="1", lock="lk")- monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")+ _worker_env(monkeypatch, recovery=2)monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- clock = iter([1_000, 1_700])- monkeypatch.setattr(rec, "_now", lambda: next(clock))- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed()-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 75 # timeout stamp → transient release; gate still vetoes- assert len(runs) == 1 # goal-on: still exactly ONE model call (was 2 before the gate)- assert goal_spy == []--[email protected]("reason", ["billing", "upstream_rate_limit"])-def test_goal_mode_does_not_continue_on_a_quota_wall(monkeypatch, goal_spy, reason):- """The neutral 75 must arrive without a sibling continuation making another- quota-bound call first — goal mode is skipped for a quota-wall result."""- _quiet_goal_env(monkeypatch)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed(reason=reason)-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")+ cli_mod, entered, ui = cli_harness(driver, [_failed(), _success()])- assert exc_info.value.code == 75- assert len(runs) == 1- assert goal_spy == []+ assert _drive(cli_mod, driver) == 0 # settled successfully+ assert len(entered) == 2 # the failed turn, then the recovery turn+ assert "Do NOT start over" in entered[1]+ assert "t_probe" in entered[1]- ("result", "expected"),- [- ({**_failed(), "interrupted": True}, 130), # explicit cancellation: 130, never continued- ({**_failed(retryable=True), "turn_exit_reason": "max_iterations_reached(60/60)"},- 75), # #87096 settlement: transient stamp → neutral release, never continued- ],- ids=["interrupt", "terminal-settlement"],-)-def test_goal_mode_does_not_continue_on_interrupt_or_terminal_settlement(- monkeypatch, goal_spy, result, expected-):- _quiet_goal_env(monkeypatch)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return result-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == expected- assert len(runs) == 1- assert goal_spy == []---def test_goal_mode_does_not_continue_after_the_recovery_budget_is_exhausted(- monkeypatch, live_claim, goal_spy-):- """Budget exhausted (recovery attempted, still failed): the goal loop must- not take over as an unbounded continuation channel past the recovery cap."""[email protected]("driver", DRIVERS)+def test_budget_exhausted_stops_and_releases(driver, cli_harness, live_claim, monkeypatch):+ """Bounded, then released: the loop stops at the cap, and the exhausted transient wall+ still reaches the dispatcher as the neutral code."""import agent.kanban_turn_recovery as rec- _quiet_goal_env(monkeypatch)- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "1")+ _worker_env(monkeypatch, recovery=1)monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed()-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 75 # exhausted transient wall: released, not counted- assert len(runs) == 2 # original + the one authorised recovery attempt- assert goal_spy == [] # …and nothing continues past the exhausted budget--- "result",- [- {"partial": True, "completed": False, "final_response": "cut off", "error": "truncated",- "messages": []},- ],- ids=["partial"],-)-def test_goal_mode_does_not_continue_on_an_unfinished_nonfailed_turn(monkeypatch, goal_spy, result):- """Pinned semantics for the gate's breadth: an unfinished-but-not-failed turn- (partial / completed=0) also does NOT continue in goal mode — only a settled,- authorized turn continues. Truncation/compression repair is owned inside the- conversation loop (#89289) and by the dispatcher, not by the goal judge."""- _quiet_goal_env(monkeypatch)- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return result-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 1- assert len(runs) == 1- assert goal_spy == []---def test_goal_mode_continues_after_a_successful_authorized_recovery(- monkeypatch, live_claim, goal_spy-):- """Positive control: goal continuation is PRESERVED for a settled,- authorized turn — recovery succeeds and the judge-driven loop runs with the- recovered response."""+ cli_mod, entered, ui = cli_harness(driver, _failed) # never recovers++ assert _drive(cli_mod, driver) == KANBAN_RATE_LIMIT_EXIT_CODE+ assert len(entered) == 2 # original + one recovery attempt+++def _single_turn_cases():+ """One row per single-turn outcome on either route: ``(env, script, exit code)``. Every+ row takes exactly ONE model turn, so what is under test is what the route does AFTER+ that turn: the neutral release for a quota wall (#48000-class boundary, including the+ aggregator's upstream 429) versus an honest 1 for a turn that is not retry authority+ (partial / nothing-settled) or for a run that is not a worker at all."""+ neutral = KANBAN_RATE_LIMIT_EXIT_CODE+ return [+ pytest.param({}, [None], 1, id="nothing-settled"),+ pytest.param({}, [_partial()], 1, id="denial-unfinished-turn"),+ pytest.param({}, [_failed(reason="rate_limit")], neutral, id="quota-wall"),+ pytest.param({}, [_failed(reason="billing")], neutral, id="billing-wall"),+ pytest.param({}, [_failed(reason="upstream_rate_limit")], neutral,+ id="upstream-quota-wall"),+ pytest.param({"task": " "}, [_failed(reason="rate_limit")], 1,+ id="blank-task-id-is-not-a-worker"),+ pytest.param({"task": None}, [_failed()], 1, id="non-worker-failed"),+ pytest.param({"task": None}, [None], 1, id="non-worker-unsettled"),+ ]++[email protected]("driver", DRIVERS)[email protected](("env", "script", "code"), _single_turn_cases())+def test_single_turn_route_outcomes(driver, env, script, code, cli_harness, live_claim,+ monkeypatch):+ """One representative end-to-end denial per driver, plus the quota-wall release and the+ non-worker rows. An unfinished, non-failed turn is not retry authority (the unit table+ above pins interrupt / terminal settlement / partial as well), so exactly one model turn+ is taken and the exit is the honest code rather than a silent rc=0; ``task=None`` means+ no worker env at all, and a blank id is not a worker either (its wall is NOT+ neutralized into 75 — raw env truthiness would)."""+ if "task" in env:+ if env["task"] is None:+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)+ monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)+ else:+ _worker_env(monkeypatch, task=env["task"])+ else:+ _worker_env(monkeypatch)+ cli_mod, entered, ui = cli_harness(driver, list(script))++ assert _drive(cli_mod, driver) == code+ assert len(entered) == 1++[email protected]("driver", DRIVERS)+def test_claim_denial_stops_before_model_reentry(driver, cli_harness, capsys, monkeypatch):+ """A worker whose run/claim proof fails gets no recovery nudge, says so, and still+ leaves the dispatcher its neutral release."""import agent.kanban_turn_recovery as rec- _quiet_goal_env(monkeypatch)- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "2")- monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- runs: list = []-- def run_conversation(*, user_message, conversation_history):- runs.append(user_message)- return _failed() if len(runs) == 1 else _success()-- cli_mod = _install_quiet_fake_cli(monkeypatch, run_conversation)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=True, toolsets="terminal")-- assert exc_info.value.code == 0- assert len(runs) == 2 # original failed turn + the recovery turn- assert goal_spy == ["done"] # continuation happened, with the recovered response---# ── the same gate on the production `-q` route (goal_mode rides `-q`) ──---def chat_goal_spy(monkeypatch):- """Spy on the `-q` goal continuation loop. Same invariant as ``goal_spy``:- the gate under test is the CALL-SITE, not the loop's own status check."""- import cli as cli_mod+ _worker_env(monkeypatch)+ monkeypatch.setattr(rec, "worker_claim_is_live", lambda: False)+ cli_mod, entered, ui = cli_harness(driver, [_failed()])- calls: list = []- monkeypatch.setattr(cli_mod, "_run_kanban_goal_loop_chat", lambda c, resp: calls.append(resp))- return calls+ assert _drive(cli_mod, driver) == KANBAN_RATE_LIMIT_EXIT_CODE+ assert len(entered) == 1+ assert "no longer holds a live run/claim" in capsys.readouterr().err-def test_non_quiet_goal_mode_does_not_continue_after_recovery_denial(- monkeypatch, chat_goal_spy+def test_non_quiet_route_prints_its_exit_summary(cli_harness, live_claim, monkeypatch):+ """Smoke pin kept from the pre-trim file: a plain (non-worker) failed `chat -q` run still+ prints its exit summary before exiting 1 — the non-quiet tail exits unconditionally, so+ the summary has to be printed on the way out."""+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)+ cli_mod, entered, ui = cli_harness("chat", [_failed()])++ assert _drive(cli_mod, "chat") == 1+ assert entered == ["hello"] # no recovery outside a worker+ assert "summary" in ui+++# ── goal mode: a refused recovery stops ALL model entry (one table) ──+++def _goal_cases():+ """One row per way model entry can be refused while goal mode is ON:+ ``(id, env setup, script, expected exit code, expected model entries)``. Each row+ carries its own setup, because the refusal reason IS the setup."""+ neutral = KANBAN_RATE_LIMIT_EXIT_CODE+ return [+ pytest.param("recovery-denied", {"live": False}, _failed, neutral, 1),+ pytest.param("lease-expired-during-backoff", {"lease_expiry": True}, _failed, neutral, 1),+ pytest.param("quota-wall-billing", {}, lambda: _failed(reason="billing"), neutral, 1),+ pytest.param("quota-wall-upstream", {}, lambda: _failed(reason="upstream_rate_limit"),+ neutral, 1),+ pytest.param("interrupt", {}, _interrupted, 130, 1),+ pytest.param("terminal-settlement", {}, _settled, neutral, 1),+ pytest.param("budget-exhausted", {"recovery": 1}, _failed, neutral, 2),+ pytest.param("unfinished-nonfailed", {}, _partial, 1, 1),+ ]++[email protected]("driver", DRIVERS)[email protected](("case_id", "setup", "script", "code", "entries"), _goal_cases())+def test_goal_mode_does_not_continue(+ case_id, setup, script, code, entries, driver, clear_kanban_env, tmp_path, monkeypatch,+ cli_harness, goal_spy,):- """The dispatcher spawns goal_mode cards on the ``-q`` route- (``kanban_db_dispatch.py`` builds ``chat -q`` and sets- ``HERMES_KANBAN_GOAL_MODE=1``), so the round-3 finding has to be closed- there too: a DENIED recovery (claim lost) reaches the shared exit path with- zero further model entry."""+ """With goal mode ON, every refusal path reaches the shared exit without a judge-driven+ continuation: the goal loop's own status check sees only run identity, not the claim+ lease, so continuing would re-enter the model under an authority this process can no+ longer prove."""import agent.kanban_turn_recovery as rec- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")- monkeypatch.setattr(rec, "worker_claim_is_live", lambda: False) # recovery denied- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed()], calls)+ clear_kanban_env.setenv("HERMES_KANBAN_GOAL_MODE", "1")+ monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))+ if setup.get("lease_expiry"):+ db = _make_board(tmp_path, task_expires=1_600, run_expires=1_600)+ _pin_carrier(clear_kanban_env, db, run_id="1", lock="lk")+ clock = iter([1_000, 1_700]) # pre-backoff proof live; the re-proof is not+ monkeypatch.setattr(rec, "_now", lambda: next(clock))+ else:+ clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_probe")+ monkeypatch.setattr(rec, "worker_claim_is_live", lambda: setup.get("live", True))+ if setup.get("recovery") is not None:+ clear_kanban_env.setenv("HERMES_KANBAN_TURN_RECOVERY", str(setup["recovery"]))- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")+ cli_mod, entered, ui = cli_harness(driver, script)- assert exc_info.value.code == 75 # transient stamp → released, not counted- assert len(_chats(calls)) == 1 # the failed turn only: no recovery nudge- assert chat_goal_spy == [] # NO goal continuation after the denial+ assert _drive(cli_mod, driver) == code+ assert len(entered) == entries+ assert goal_spy == [] # no continuation after a refused recovery-def test_non_quiet_goal_mode_continues_after_a_successful_authorized_recovery(- monkeypatch, live_claim, chat_goal_spy[email protected]("driver", DRIVERS)+def test_goal_mode_continues_after_a_successful_authorized_recovery(+ driver, cli_harness, live_claim, goal_spy, monkeypatch,):- """Positive control on the ``-q`` route: a settled, authorized turn still- continues in goal mode — the gate must not swallow the happy path — and the- judge receives the RECOVERED response, not the initial provider error."""+ """Positive control on both drivers: a settled, authorized recovery still continues in+ goal mode — the veto must not swallow the happy path — and the judge receives the+ RECOVERED response, not the initial provider error (re-review P2: the recovery+ callback's return value carries through)."""import agent.kanban_turn_recovery as rec- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_probe")- monkeypatch.setenv("HERMES_KANBAN_GOAL_MODE", "1")- monkeypatch.setenv("HERMES_KANBAN_TURN_RECOVERY", "2")+ _worker_env(monkeypatch, goal_mode=True, recovery=2)monkeypatch.setattr(rec, "RECOVERY_DELAYS_SECONDS", (0.0,))- calls: list = []- cli_mod = _install_fake_cli(monkeypatch, [_failed(), _success()], calls)-- with pytest.raises(SystemExit) as exc_info:- cli_mod.main(query="hello", quiet=False, oneshot=True, toolsets="terminal")+ cli_mod, entered, ui = cli_harness(driver, [_failed(), _success()])- assert exc_info.value.code == 0- assert len(_chats(calls)) == 2- # …and the judge must receive the RECOVERED response, not the initial provider- # error (re-review P2): the recovery callback's return value carries through.- assert chat_goal_spy == ["done"]+ assert _drive(cli_mod, driver) == 0+ assert len(entered) == 2+ assert goal_spy == [("done", driver)]