Skip to content

The agent that grows with you

fix(compressor): don't move a merged tool-call carrier during replay dedup

kshitijk4poor2667c960d506
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index a660cc4cbd1..b43f907c73a 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -5047,6 +5047,7 @@ Write only the summary body. Do not include any preamble or prefix."""
if replay_uid := message_uid_or_none(replay):
before = len(compressed)
+ kept = list(compressed)
compressed[:] = [
msg
for msg in compressed
@@ -5061,7 +5062,13 @@ Write only the summary body. Do not include any preamble or prefix."""
# leading model functionCall turn. Open the window on the carrier.
first = next(i for i, msg in enumerate(compressed) if msg.get("role") != "system")
if len(compressed) != before and compressed[first].get("role") != "user":
- compressed.insert(first, compressed.pop(compressed.index(carrier)))
+ if _template_visible_role(carrier) is None:
+ # Carrier merged into a tail assistant(tool_calls) row:
+ # moving it would split it from its tool results. Keep
+ # the head row this cycle (pre-dedup layout).
+ compressed[:] = kept
+ else:
+ compressed.insert(first, compressed.pop(compressed.index(carrier)))
# The summary role was picked against a head that ended on the row
# just removed: an assistant carrier would now open the visible
# sequence (or follow an assistant). Use the _force_user_leading
diff --git a/tests/agent/test_cron_inflight_prompt_reappend.py b/tests/agent/test_cron_inflight_prompt_reappend.py
index ce6acce4a0a..a60d6976557 100644
--- a/tests/agent/test_cron_inflight_prompt_reappend.py
+++ b/tests/agent/test_cron_inflight_prompt_reappend.py
@@ -402,3 +402,13 @@ def test_replay_replaces_surviving_user_row_with_same_message_uid():
assert visible[0] == "user", visible
assert all(a != b for a, b in zip(visible, visible[1:])), visible
assert JOB_SENTINEL in _text(compressed[_handoff_idx(compressed)]).split(_SUMMARY_END_MARKER)[-1]
+
+ # Visible assistant text in the tail makes the summary merge into tail[0],
+ # an assistant(tool_calls) row: it must stay adjacent to its tool results.
+ messages += [{"role": "assistant", "content": "interim note"}, *_tool_pairs(1, 40)]
+ compressed = _compress(messages)
+ assert compressed[1]["role"] == "user", [m["role"] for m in compressed]
+ for i, msg in enumerate(compressed):
+ if msg.get("tool_calls"):
+ ids = [c["id"] for c in msg["tool_calls"]]
+ assert [m.get("tool_call_id") for m in compressed[i + 1 : i + 1 + len(ids)]] == ids, i