Skip to content

The agent that grows with you

fix(compressor): keep alternation when the in-flight replay drops the head user row

kshitijk4poor7b3fc99ce87d
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 2daecdf9411..c8222570325 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -5045,6 +5045,7 @@ Write only the summary body. Do not include any preamble or prefix."""
# same message_uid and renders the request twice after reload.
replay_uid = replay.get("message_uid")
if isinstance(replay_uid, str) and replay_uid:
+ before = len(compressed)
compressed[:] = [
msg
for msg in compressed
@@ -5054,6 +5055,15 @@ Write only the summary body. Do not include any preamble or prefix."""
and msg.get("message_uid") == replay_uid
)
]
+ # 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
+ # layout instead — carrier role=user, request after its end marker.
+ if len(compressed) != before and _template_visible_role(carrier) == "assistant" and (
+ _last_template_visible_role(compressed[: compressed.index(carrier)]) in {None, "system", "assistant"}
+ ):
+ carrier["role"] = "user"
+ last_visible_role = _last_template_visible_role(compressed)
if last_visible_role == "user":
# Alternation is judged on template-visible rows only (tool_calls /
diff --git a/tests/agent/test_cron_inflight_prompt_reappend.py b/tests/agent/test_cron_inflight_prompt_reappend.py
index a258e37b67f..8f34d1182b5 100644
--- a/tests/agent/test_cron_inflight_prompt_reappend.py
+++ b/tests/agent/test_cron_inflight_prompt_reappend.py
@@ -377,6 +377,24 @@ def test_replay_replaces_surviving_user_row_with_same_message_uid():
[original, carrier], {**original}
)
- matching = [m for m in out if m.get("message_uid") == uid]
+ def holders(rows):
+ return [m for m in rows if uid == m.get("message_uid") or uid in m.get("_absorbed_message_uids", ())]
+
+ matching = holders(out)
assert len(matching) == 1
assert _INFLIGHT_TASK_REPLAY_HEADER in str(matching[0].get("content"))
+
+ # Real compress(): the head-protected original is the head's only user row.
+ # Removing it must not leave the window opening system -> assistant.
+ messages = _cron_transcript()
+ messages[1] = {**messages[1], "message_uid": uid}
+ compressed = _compress(messages)
+ assert len(holders(compressed)) == 1
+ visible = [
+ m["role"]
+ for m in compressed[1:]
+ if not (m["role"] == "tool" or (m["role"] == "assistant" and m.get("tool_calls")))
+ ]
+ 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]