The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(loop): re-anchor current_turn_user_idx after the alternation repair merges rows
Felipe Portavalesfe21a4d2f082
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex a6541073d1a..fe7e56c74aa 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -89,9 +89,12 @@ class IterationPrep:action: strmessages: Anyrequest_logger: Any+ current_turn_user_idx: Any-def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> IterationPrep:+def prepare_iteration(+ agent: Any, *, messages: Any, api_call_count: Any, user_message: Any = None, current_turn_user_idx: Any = None,+) -> IterationPrep:"""Prepare ``messages`` for this iteration in the original order. Every mutation here iscache-safe by construction: steer text lands in the newest tool result, the ghost-rowfilter only drops hidden scaffold placeholders, and repair runs BEFORE the request build."""@@ -182,7 +185,31 @@ def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> Iterarepaired_seq,agent.session_id or "-",)- return IterationPrep(action="fallthrough", messages=messages, request_logger=request_logger)+ # The repair merges adjacent user rows in place (after a compaction the role=user+ # summary sits next to the protected first user message), so the list shrinks and+ # the index recorded at turn start points past this turn's user row. Re-anchor it+ # like the compression restart path does, and mirror the value into+ # _persist_user_message_idx, which hosts read when the result carries no index:+ # a stale anchor injects prefetch into a historical row and makes hosts that settle+ # their transcript by this index (hermes-webui) write the current turn to the FRONT+ # of the context, rewriting the prompt's leading messages every turn.+ _reanchored_idx = (+ reanchor_current_turn_user_idx(messages, user_message) if user_message is not None+ else current_turn_user_idx+ )+ if _reanchored_idx != current_turn_user_idx:+ request_logger.info(+ "Re-anchored current_turn_user_idx %s -> %s after alternation repair (session=%s)",+ current_turn_user_idx,+ _reanchored_idx,+ agent.session_id or "-",+ )+ current_turn_user_idx = _reanchored_idx+ agent._persist_user_message_idx = _reanchored_idx+ return IterationPrep(+ action="fallthrough", messages=messages, request_logger=request_logger,+ current_turn_user_idx=current_turn_user_idx,+ )def _previous_tool_round(messages: Any) -> list:diff --git a/tests/run_agent/test_repair_reanchors_current_turn_user_idx.py b/tests/run_agent/test_repair_reanchors_current_turn_user_idx.pynew file mode 100644index 00000000000..a307794117e--- /dev/null+++ b/tests/run_agent/test_repair_reanchors_current_turn_user_idx.py@@ -0,0 +1,50 @@+"""Regression: ``repair_message_sequence`` merges adjacent rows *before* the current+turn's user message (a role=user compaction summary next to the protected first+user message), so the index recorded at turn start drifts past the current row.+Hosts that settle the transcript by that index (WebUI) then write the current+user turn to the FRONT of the context. ``run_conversation`` must re-anchor the+index after a repair that changed the list.+"""+from agent.agent_runtime_helpers import repair_message_sequence+from agent.turn_context import reanchor_current_turn_user_idx+++class _Agent:+ session_id = "s"+++def _history_with_adjacent_users():+ return [+ {"role": "assistant", "content": "**Context snapshot**"},+ {"role": "user", "content": "compaction summary written as a user row"},+ {"role": "user", "content": "first protected user message"},+ {"role": "assistant", "content": "ok",+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "t", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "out"},+ {"role": "user", "content": "NEW question"},+ ]+++def test_repair_shifts_recorded_index_and_reanchor_recovers_it():+ messages = _history_with_adjacent_users()+ recorded_idx = len(messages) - 1 # what run_conversation records at turn start+ assert messages[recorded_idx]["content"] == "NEW question"+ repairs = repair_message_sequence(_Agent(), messages)+ assert repairs >= 1+ # the recorded index no longer addresses the current user row+ assert recorded_idx >= len(messages) or messages[recorded_idx]["content"] != "NEW question"+ reanchored = reanchor_current_turn_user_idx(messages, "NEW question")+ assert messages[reanchored]["role"] == "user"+ assert messages[reanchored]["content"] == "NEW question"+ assert reanchored == len(messages) - 1+++def test_repair_without_changes_keeps_index():+ messages = [+ {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "hi"},+ {"role": "user", "content": "NEW question"},+ ]+ recorded_idx = len(messages) - 1+ assert repair_message_sequence(_Agent(), messages) == 0+ assert reanchor_current_turn_user_idx(messages, "NEW question") == recorded_idx