Skip to content

The agent that grows with you

refactor(agent): one predicate for the resumable iteration-cap handoff

Austin Pickett5f5c9ef8f468
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index 41f3c808fe3..0776ac6d133 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -127,6 +127,23 @@ def exit_reason_failure(turn_exit_reason: Any) -> Optional[ExitFailure]:
return None
+def is_max_iteration_handoff(result: Any) -> bool:
+ """A non-failed, non-interrupted ``max_iterations_reached(N/N)`` result that still carries a
+ summary. ``completed`` is False because the work did not finish in that turn, but the turn
+ itself is a resumable boundary — not a failure — so cron delivers the summary and an active
+ ``/goal`` may judge it (#102213). Provider/API failures never match (cf. #63180)."""
+ if not isinstance(result, dict):
+ return False
+ if result.get("failed") is True or result.get("interrupted") is True:
+ return False
+ if result.get("completed") is not False:
+ return False
+ reason = result.get("turn_exit_reason")
+ if not (isinstance(reason, str) and reason.startswith("max_iterations_reached(")):
+ return False
+ return bool(str(result.get("final_response") or "").strip())
+
+
# ---- chat copy tables -----------------------------------------------------------------------
_NEXT_STEPS_RETRY = "Wait a minute and send /retry, or switch models with /model."
diff --git a/cron/scheduler.py b/cron/scheduler.py
index f2d2f9db0dc..1d156c0d6e6 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -46,6 +46,7 @@ from agent.interrupt_compat import request_hard_interrupt
from agent.delegation_context import (
enter_non_dispatcher_owned_context, exit_non_dispatcher_owned_context)
from agent.memory_provider import ctx_bound
+from agent.turn_failure_copy import is_max_iteration_handoff
logger = logging.getLogger(__name__)
@@ -1983,12 +1984,7 @@ def _final_response_from_result(result: dict, job_id: str, job_name: str, AIAgen
# Raise so the except handler below builds the proper failure tuple. (issue #17855)
turn_exit_reason = str(result.get("turn_exit_reason") or "")
final_response_text = (result.get("final_response") or "").strip()
- max_iteration_summary = (
- result.get("failed") is not True
- and result.get("completed") is False
- and turn_exit_reason.startswith("max_iterations_reached(")
- and bool(final_response_text)
- )
+ max_iteration_summary = is_max_iteration_handoff(result)
if result.get("failed") is True or (result.get("completed") is False and not max_iteration_summary):
raise RuntimeError(result.get("error") or final_response_text or "agent reported failure")
if max_iteration_summary:
diff --git a/tests/agent/test_max_iteration_handoff.py b/tests/agent/test_max_iteration_handoff.py
new file mode 100644
index 00000000000..358838932bc
--- /dev/null
+++ b/tests/agent/test_max_iteration_handoff.py
@@ -0,0 +1,41 @@
+"""Shared classification of a non-failed iteration-cap turn (#102213).
+
+Cron delivery and the TUI ``/goal`` judge gate must agree on what a resumable
+``max_iterations_reached`` handoff is, so both read one predicate instead of
+parsing the exit reason independently.
+"""
+
+import pytest
+
+from agent.turn_failure_copy import is_max_iteration_handoff
+from cron.scheduler import _final_response_from_result
+
+_HANDOFF = {
+ "final_response": "checkpoint: two of three steps done",
+ "completed": False,
+ "failed": False,
+ "interrupted": False,
+ "turn_exit_reason": "max_iterations_reached(3/3)",
+}
+
+
+ ("override", "expected"),
+ [
+ ({}, True),
+ ({"failed": True}, False),
+ ({"interrupted": True}, False),
+ ({"completed": True}, False),
+ ({"turn_exit_reason": "budget_exhausted"}, False),
+ ({"turn_exit_reason": "error_near_max_iterations(3/3)"}, False),
+ ({"final_response": " "}, False),
+ ],
+)
+def test_only_a_non_failed_capped_turn_with_a_summary_is_a_handoff(override, expected):
+ assert is_max_iteration_handoff({**_HANDOFF, **override}) is expected
+
+
+def test_cron_delivers_exactly_the_handoffs_the_predicate_accepts():
+ assert _final_response_from_result(dict(_HANDOFF), "j", "job", object) == _HANDOFF["final_response"]
+ with pytest.raises(RuntimeError):
+ _final_response_from_result({**_HANDOFF, "failed": True}, "j", "job", object)
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index 39497c941e7..fa93f43580d 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -49,23 +49,17 @@ def _hook_failure(what: str, exc: BaseException) -> None:
def _is_successful_goal_turn(result: Any, status: str, raw: Any) -> bool:
"""Whether a turn produced a real response the goal judge can use.
- A non-failed ``max_iterations_reached(...)`` handoff is a resumable
- turn boundary, not a failure: the summary must reach the goal judge
- so an active goal can continue (#102213). Failed, interrupted, and
- other ``completed is False`` turns still stay out (cf. #63180).
- """
+ A non-failed ``max_iterations_reached(...)`` handoff is a resumable turn boundary, not a
+ failure: its summary must reach the judge so an active goal continues (#102213). Failed,
+ interrupted and other ``completed is False`` turns still stay out (cf. #63180)."""
+ from agent.turn_failure_copy import is_max_iteration_handoff
if status != "complete" or not isinstance(raw, str) or not raw.strip():
return False
if not isinstance(result, dict):
return True
if result.get("failed") or result.get("interrupted"):
return False
- if result.get("completed") is False:
- reason = result.get("turn_exit_reason") or ""
- return isinstance(reason, str) and reason.startswith(
- "max_iterations_reached"
- )
- return True
+ return result.get("completed") is not False or is_max_iteration_handoff(result)
def _active_goal_manager(session: dict):