The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a refused turn never drives /goal or a /loop --until judge
Teknium358f3e8473b9
diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex 2dad28e8255..99271d77018 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -365,13 +365,16 @@ class GatewayGoalsMixin:logger.debug("post-turn session resolution failed: %s", exc)return# Empty interrupted/errored responses must not drive /goal, but an in-flight /loop tick- # still needs to be released and rescheduled.+ # still needs to be released and rescheduled. A failed turn with text (a refusal: its+ # folder is gone) is no evidence either (the TUI's hook skips it the same way): the tick is+ # released with no text, so a --until judge never grades it.+ failed = self._turn_failed()hooks = [("loop completion", self._post_turn_loop_completion)]- if final_text.strip():+ if final_text.strip() and not failed:hooks.insert(0, ("goal continuation", self._post_turn_goal_continuation))for label, hook in hooks:try:- await hook(session_entry=session_entry, source=source, final_response=final_text)+ await hook(session_entry=session_entry, source=source, final_response="" if failed else final_text)except Exception as exc:logger.debug("%s hook failed: %s", label, exc)self._publish_local_control(source, only_if_present=True)@@ -385,6 +388,15 @@ class GatewayGoalsMixin:from gateway.session_control_actions import publishpublish(active_authority(self), source.chat_id, only_if_present=only_if_present)+ @staticmethod+ def _turn_failed() -> bool:+ """Whether the owner recorded this turn's result as failed (``session_ingress`` captures it+ around ``_handle_message``; turns outside an owner capture nothing)."""+ from gateway.session_results import execution_result+ captured = execution_result.get() or {}+ result = captured.get('terminal_result', captured.get('result'))+ return isinstance(result, dict) and bool(result.get('failed'))+@staticmethoddef _final_text_for_post_turn_hooks(agent_result, event=None) -> str:"""Text for /goal and /loop after a gateway turn. Streamed turns return None fromdiff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.pyindex e2677626353..5becdf58bfa 100644--- a/hermes_cli/cli_chat_turn_mixin.py+++ b/hermes_cli/cli_chat_turn_mixin.py@@ -64,6 +64,7 @@ class CLIChatTurnMixin:set_secret_capture_callback(self._secret_capture_callback)# Reset per turn; only a real interrupt flips it, so early returns leave it False.self._last_turn_interrupted = False+ self._last_turn_failed = Falseif not self._ensure_runtime_credentials():return None@@ -608,6 +609,8 @@ class CLIChatTurnMixin:_interrupted_this_turn = bool(turn.result and turn.result.get("interrupted"))# Post-turn hooks (e.g. goal continuation) skip themselves on a user-cancelled turn.self._last_turn_interrupted = _interrupted_this_turn+ # ... and on a failed one (a refused turn, a provider error): nothing to judge.+ self._last_turn_failed = bool(turn.result and turn.result.get("failed"))if _interrupted_this_turn:pending_message = turn.result.get("interrupt_message") or interrupt_msg_show_interrupt_marker = bool(response and pending_message)diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.pyindex b7b191dafcd..8041a09c750 100644--- a/hermes_cli/cli_loops_mixin.py+++ b/hermes_cli/cli_loops_mixin.py@@ -806,7 +806,8 @@ class CLILoopsMixin:pass_cprint(f" {_DIM}{t('cli.loop.paused_interrupted')}{_RST}")return- decision = mgr.complete_tick(self._last_assistant_response_text())+ decision = mgr.complete_tick("" if getattr(self, "_last_turn_failed", False)+ else self._last_assistant_response_text())# With the live-work dock up its loop row carries the countdown; the one-shot line would go stale.if (not _print_decision_message(decision) and decision.get("status") == "active"and mgr.state is not None and getattr(self, "_subagent_monitor", None) is None):@@ -851,6 +852,10 @@ class CLILoopsMixin:# Empty/whitespace responses are almost always transient failures (API error,# empty stream): judging would say "continue" and trip the parse-failure backstop.+ # A failed turn (a refused one: its folder is gone) never reached the model, so the judge+ # would grade the previous reply and burn the whole budget; same rule as the TUI's hook.+ if getattr(self, "_last_turn_failed", False):+ returnlast_response = self._last_assistant_response_text()if not last_response.strip():returndiff --git a/tests/gateway/test_loop_command.py b/tests/gateway/test_loop_command.pyindex 19214684928..7a1ed16386a 100644--- a/tests/gateway/test_loop_command.py+++ b/tests/gateway/test_loop_command.py@@ -213,6 +213,38 @@ async def test_empty_agent_result_releases_inflight_loop_tick(loop_env):assert reloaded.next_due_at > time.time()+async def test_failed_turn_with_text_never_drives_goal_or_until_judge(loop_env, monkeypatch):+ """A refused turn (its folder is gone) settles failed WITH text. That text is not evidence: the+ goal judge must not run on it (it burned the whole turn budget in seconds) and the /loop tick is+ released with no text, so a --until judge never grades it; the loop still reschedules."""+ from gateway.session_results import execution_result+ from hermes_cli import goals++ runner = _make_runner()+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI --until CI is green"))+ mgr = loops.LoopManager(session_id="sid-gateway-loop")+ mgr.state.next_due_at = time.time() - 1+ assert mgr.fire_tick() is not None++ judged = []+ monkeypatch.setattr(goals, "judge_goal", lambda *a, **k: judged.append(a) or ("done", "green", False, None, False))+ runner._post_turn_goal_continuation = AsyncMock()+ refusal = "⚠️ This chat's working folder no longer exists (/gone), so your message was not run."+ token = execution_result.set({"result": {"final_response": refusal, "failed": True, "completed": False}})+ try:+ await GatewayRunner._run_post_turn_hooks(+ runner, agent_result=refusal, source=_make_event("wakeup").source, is_internal=True,+ )+ finally:+ execution_result.reset(token)++ runner._post_turn_goal_continuation.assert_not_awaited()+ assert judged == []+ reloaded = loops.load_loop("sid-gateway-loop")+ assert reloaded.awaiting_response is False and reloaded.status == "active"++@pytest.mark.asyncioasync def test_goal_hook_failure_does_not_block_loop_completion(loop_env, caplog):runner = _make_runner()