Skip to content

The agent that grows with you

fix(agent): judge "wrong script" against the user's own message; one continuation kind per stop

kshitijk4poor112446afd1b2
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 5c9974862c5..7ff760954de 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2962,30 +2962,46 @@ def looks_like_codex_intermediate_ack(
# Degenerate-final detector (#103483): after real tool work a text stop whose ENTIRE answer is a
-# fragment — a stray wrong-script word ("пар"), a token starting mid-punctuation ("?warming up") —
-# is a provider-side collapse, not an answer, yet the loop accepted it and the turn reported
-# completed. Shape alone cannot PROVE a collapse, so this is deliberately narrower than "short":
-# a terse legitimate answer ("42", "SQLite", "report.csv", "€12.50", "你好。", "Done.") never
-# matches, and the re-prompt it triggers asks for the same answer again if it was complete.
+# fragment — a stray wrong-script word ("пар" in an English conversation), a token starting
+# mid-punctuation ("?warming up") — is a provider-side collapse, not an answer, yet the loop
+# accepted it and the turn reported completed. Shape alone cannot PROVE a collapse, so this is
+# deliberately narrower than "short": a terse legitimate answer ("42", "SQLite", "report.csv",
+# "€12.50", "你好。", "Done.", ":8080", "да" to a Russian prompt) never matches, English-script
+# fragments ("the", "ing") are knowingly not covered, and the re-prompt it triggers asks for the
+# same answer again if it was complete. ``turn_finalizer._SENTENCE_END`` encodes the same
+# "≤ 24 chars, no terminal" heuristic for the finish explainer.
_DEGENERATE_FINAL_MAX_CHARS = 24
_SENTENCE_TERMINALS = (".", "!", "?", "\u3002", "\uff01", "\uff1f")
-# Punctuation no answer begins with; "$5", "#123", "-1", "/tmp", ".env", "(a)" all stay answers.
+# Punctuation no answer begins with when a letter follows ("?warming"); "$5", "#123", "-1",
+# "/tmp", ".env", "(a)", ":8080", ":)", ";;" all stay answers.
_DEGENERATE_LEADING_PUNCT = "?!,;:)]}"
-def looks_like_degenerate_final(text: str) -> bool:
- """Whether a text stop reads as a collapsed fragment rather than a (terse) answer."""
+def looks_like_degenerate_final(text: str, user_message: Any = None) -> bool:
+ """Whether a text stop reads as a collapsed fragment rather than a (terse) answer.
+
+ "Wrong script" is judged against the conversation: when the user's own message carries
+ non-ASCII letters, a terse non-Latin reply ("是", "Готово") is an answer, not a collapse.
+ """
t = (text or "").strip()
if not t or len(t) > _DEGENERATE_FINAL_MAX_CHARS or t.endswith(_SENTENCE_TERMINALS):
return False
- if t[0] in _DEGENERATE_LEADING_PUNCT:
+ if t[0] in _DEGENERATE_LEADING_PUNCT and len(t) > 1 and t[1].isalpha():
return True
- # A word with letters but no ASCII letter or digit at all: the wrong-script fragment.
- return any(ch.isalpha() for ch in t) and not any(ch.isascii() and ch.isalnum() for ch in t)
+ if not any(ch.isalpha() for ch in t) or any(ch.isascii() and ch.isalnum() for ch in t):
+ return False
+ from agent.codex_responses_adapter import _summarize_user_message_for_log
+ user_text = _summarize_user_message_for_log(user_message) if user_message else ""
+ return not any(ch.isalpha() and not ch.isascii() for ch in user_text)
def tool_results_this_turn(messages: List[Dict[str, Any]]) -> int:
- """Tool-result rows after the most recent user row — whether the turn did real tool work."""
+ """Tool-result rows after the most recent user row — whether the turn did real tool work.
+
+ ANY user row ends the window, the continuation nudges included: that is what bounds the
+ degenerate-final guard to one re-prompt per collapse. Skipping synthetic user rows here
+ would turn it into a two-nudge loop.
+ """
count = 0
for msg in reversed(messages or ()):
if not isinstance(msg, dict):
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index dd568cf2173..af36bc717f7 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -167,14 +167,20 @@ def finish_text_response(
# Degenerate-final guard (#103483): the turn did real tool work and then stopped on a
# fragment. Same scope knob and the SAME bounded counter as the ack continuation; the nudge
# row itself closes the tool-work window, so a second fragment ends the turn as the answer.
+ _tool_rows = tool_results_this_turn(messages)
_degenerate_final = (
bool(getattr(agent, "_stall_guards", True))
and _ack_mode != "off"
and codex_ack_continuations < 2
- and tool_results_this_turn(messages) > 0
- and looks_like_degenerate_final(_stall_text)
+ and _tool_rows > 0
+ and looks_like_degenerate_final(_stall_text, user_message=user_message)
)
- if _stall_continue_intent or _degenerate_final or (
+ # Precedence: an announced next action outranks the fragment shape; the codex ack is last.
+ if _stall_continue_intent:
+ _continuation_kind = "stall"
+ elif _degenerate_final:
+ _continuation_kind = "degenerate"
+ elif (
_ack_mode != "off"
and agent.valid_tool_names
and codex_ack_continuations < 2
@@ -183,17 +189,21 @@ def finish_text_response(
require_workspace=(_ack_mode == "codex_only"),
)
):
- if _stall_continue_intent:
+ _continuation_kind = "ack"
+ else:
+ _continuation_kind = None
+ if _continuation_kind:
+ if _continuation_kind == "stall":
logger.info(
"Stall guard: turn ending on trailing continue-"
"intent with no tool calls — re-prompting to act "
"(%d/2)", codex_ack_continuations + 1,
)
- elif _degenerate_final:
+ elif _continuation_kind == "degenerate":
logger.warning(
"Degenerate final: %d-char fragment %r ended the turn after %d tool result(s) — "
- "re-prompting (%d/2)", len(_stall_text), _stall_text[:40],
- tool_results_this_turn(messages), codex_ack_continuations + 1,
+ "re-prompting (%d/2)", len(_stall_text), _stall_text[:40], _tool_rows,
+ codex_ack_continuations + 1,
)
codex_ack_continuations += 1
interim_msg = agent._build_assistant_message(assistant_message, "incomplete")
@@ -206,7 +216,7 @@ def finish_text_response(
append_message(messages, {
"role": "user",
"content": (
- _DEGENERATE_FINAL_NUDGE if _degenerate_final and not _stall_continue_intent
+ _DEGENERATE_FINAL_NUDGE if _continuation_kind == "degenerate"
else _CODEX_ACK_CONTINUATION_NUDGE
),
})
diff --git a/tests/agent/test_degenerate_final_recovery.py b/tests/agent/test_degenerate_final_recovery.py
index 573b7b313cc..5bfd654a6f7 100644
--- a/tests/agent/test_degenerate_final_recovery.py
+++ b/tests/agent/test_degenerate_final_recovery.py
@@ -106,15 +106,27 @@ class TestFragmentAfterToolWork:
class TestLooksLikeDegenerateFinal:
- @pytest.mark.parametrize("text", ["пар", "?warming up", ",and", "ошибка", "你好", "):"])
- def test_fragments(self, text):
- assert looks_like_degenerate_final(text)
+ EN = "Build the workbook and report back."
+
+ @pytest.mark.parametrize("text", ["пар", "?warming up", ",and", "ошибка", "!warming"])
+ def test_fragments_in_an_english_conversation(self, text):
+ assert looks_like_degenerate_final(text, user_message=self.EN)
@pytest.mark.parametrize("text", [
# Terse legitimate answers that reviewers showed a shape-only guard re-prompting (#111472).
"42", "SQLite", "report.csv", "3.14159", "€12.50", "你好。", "Done.", "True", "a51143fbbe",
"2026-09-19", "/tmp/out.log", "$5", "#123", "-1", "(a)", ".env", "~/x", "+1", "✅",
+ ":8080", "::1", ":)", ";;", ":=", "}", "N/A", "**Done**", "`ok`", "{}", "null",
"Reading is a skill", "The answer is 43.", "x" * 25, "",
])
def test_terse_answers_are_not_fragments(self, text):
- assert not looks_like_degenerate_final(text)
+ assert not looks_like_degenerate_final(text, user_message=self.EN)
+
+ @pytest.mark.parametrize("prompt, text", [
+ ("把工作簿建好然后告诉我", "是"), ("把工作簿建好然后告诉我", "已完成"),
+ ("Собери таблицу и отчитайся", "Готово"), ("Собери таблицу и отчитайся", "да"),
+ ("ワークブックを作って報告して", "はい"), ("أنشئ المصنف ثم أخبرني", "تم"),
+ ([{"type": "text", "text": "Собери таблицу"}], "нет"), # multi-part user content
+ ])
+ def test_terse_answers_in_the_users_own_script_are_not_fragments(self, prompt, text):
+ assert not looks_like_degenerate_final(text, user_message=prompt)