The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compressor): keep pending tool_calls, avoid double anchors, no header stacking
kshitijk4poorab73aeff055f
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 8c11bd18001..48cdd330606 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -525,6 +525,12 @@ _MERGED_SUMMARY_DELIMITER = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]# the handoff boundary (#100818). A cron run's only user turn is the job prompt# in the protected head, so compaction leaves it BEFORE the summary — and# SUMMARY_PREFIX tells the model to do nothing when no user message follows.+# Set on a compaction carrier when the in-flight task was merged onto it (the+# carrier ends the list, so a standalone user row would break alternation).+# conversation_compression._ensure_compressed_has_user_turn treats it as+# "intent present" so it does not insert a second copy of the same request.+_INFLIGHT_REPLAY_MERGED_KEY = "_inflight_replay_merged"+_INFLIGHT_TASK_REPLAY_HEADER = ("[STILL IN PROGRESS — this is the active request, restated after the ""compaction boundary because it was not finished yet. Continue it; do not "@@ -6720,12 +6726,20 @@ This compaction should PRIORITISE preserving all information related to the focuwhose only user-role row is an inherited summary yields ``None`` and isnever re-animated (#80622)."""+ from agent.conversation_compression import _is_real_user_message+last_user_idx = -1for i in range(len(messages) - 1, -1, -1):msg = messages[i]- if cls._is_actionable_user_turn(- msg- ) and not cls._is_synthetic_compression_user_turn(msg):+ # _is_real_user_message also rejects metadata-flagged scaffolding+ # (_todo_snapshot_synthetic, recovery nudges, ...) that+ # _is_actionable_user_turn cannot see.+ if cls._is_actionable_user_turn(msg) and _is_real_user_message(msg):+ last_user_idx = i+ break+ if isinstance(msg, dict) and msg.get(_INFLIGHT_REPLAY_MERGED_KEY):+ # A previous cycle merged the live request onto this summary+ # carrier; it is the only copy left, so it is still the task.last_user_idx = ibreakif last_user_idx < 0:@@ -6793,6 +6807,12 @@ This compaction should PRIORITISE preserving all information related to the focureturn compressedtask_text = _content_text_for_contains(inflight.get("content")).strip()+ if _INFLIGHT_TASK_REPLAY_HEADER in task_text:+ # Already a restatement from an earlier compaction (standalone row+ # or merged onto a carrier): take the text after the header so a+ # task that survives >1 cycle never stacks headers or drags the+ # old summary along.+ task_text = task_text.rsplit(_INFLIGHT_TASK_REPLAY_HEADER, 1)[1].strip()if not task_text:return compressed@@ -6816,22 +6836,42 @@ This compaction should PRIORITISE preserving all information related to the focu),None,)+ if inflight.get(_INFLIGHT_REPLAY_MERGED_KEY):+ # Never copy a summary carrier (metadata would mark the replay+ # synthetic): restate as a plain user row.+ replay = {"role": "user", "content": task_text}+ else:+ replay = _fresh_compaction_message_copy(inflight)+ replay.pop(_COMPACTION_TAIL_MARKER, None)+ if isinstance(replay.get("content"), str):+ # Plain text: rebuild from the header-stripped task text so a+ # task surviving several compactions never stacks headers.+ replay["content"] = _INFLIGHT_TASK_REPLAY_HEADER + "\n" + task_text+ else:+ # Multimodal parts: keep them, prepend the header text part.+ replay["content"] = _append_text_to_content(+ replay.get("content"),+ _INFLIGHT_TASK_REPLAY_HEADER + "\n",+ prepend=True,+ )+ drop_stale_api_content(replay)+if last_visible_role == "user":+ # Alternation is judged on template-visible rows only (tool_calls /+ # tool rows are exempt), so a user-pinned summary followed by a+ # tool tail still "ends on user": a standalone user row would break+ # the Mistral-style pre-flight check (#58753). Merge onto the+ # carrier instead and flag it — the carrier's own metadata marks it+ # synthetic, and without the flag _ensure_compressed_has_user_turn+ # would insert a second copy of the same request.carrier["content"] = _append_text_to_content(carrier.get("content"),"\n\n" + _INFLIGHT_TASK_REPLAY_HEADER + "\n" + task_text,)+ carrier[_INFLIGHT_REPLAY_MERGED_KEY] = Truedrop_stale_api_content(carrier)return compressed- replay = _fresh_compaction_message_copy(inflight)- replay.pop(_COMPACTION_TAIL_MARKER, None)- replay["content"] = _append_text_to_content(- replay.get("content"),- _INFLIGHT_TASK_REPLAY_HEADER + "\n",- prepend=True,- )- drop_stale_api_content(replay)compressed.append(replay)return compressed@@ -8675,14 +8715,17 @@ This compaction should PRIORITISE preserving all information related to the focu# handoff (single-prompt cron shape: the job prompt is pinned in the# protected head). SUMMARY_PREFIX reads that as "no user message after# the summary → do nothing", so restate it past the boundary (#100818).+ # Run BEFORE the in-flight re-append: the sanitizer's trailing-in-flight+ # exemption (#79278) walks back from the list end, and a replay user row+ # sitting there would make a genuinely pending assistant(tool_calls) look+ # orphaned and get its calls stripped.+ compressed = self._sanitize_tool_pairs(compressed)compressed = self._reappend_inflight_user_task(compressed, self._find_inflight_user_task(messages))self.compression_count += 1- compressed = self._sanitize_tool_pairs(compressed)-# Replace image parts in all compressed messages before the newest# image-bearing user turn with a short text placeholder. Without# this, tail messages keep their original multi-MB base-64 imagediff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex edc7f2c3859..61845604998 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -3168,6 +3168,15 @@ def _ensure_compressed_has_user_turn(return "already_present"if _compressed_has_busy_steer(compressed):return "already_present"+ from agent.context_compressor import _INFLIGHT_REPLAY_MERGED_KEY++ if any(+ isinstance(message, dict) and message.get(_INFLIGHT_REPLAY_MERGED_KEY)+ for message in compressed+ ):+ # The in-flight request was restated onto the summary carrier+ # (#100818); inserting an anchor would duplicate it.+ return "already_present"from agent.context_compressor import (COMPRESSION_CONTINUATION_USER_CONTENT,_fresh_compaction_message_copy,diff --git a/tests/agent/test_cron_inflight_prompt_reappend_100818.py b/tests/agent/test_cron_inflight_prompt_reappend_100818.pyindex 2296e1607c8..ef1f8ccf249 100644--- a/tests/agent/test_cron_inflight_prompt_reappend_100818.py+++ b/tests/agent/test_cron_inflight_prompt_reappend_100818.py@@ -212,3 +212,122 @@ def test_completed_exchange_is_not_replayed():assert not any(JOB_SENTINEL in _text(m) for m in _actionable_user_rows(after)), "a completed exchange must not be re-appended as a new user instruction"+++# ---------------------------------------------------------------------------+# Follow-up coverage (salvage of #101170)+# ---------------------------------------------------------------------------+++def _pending_tail_transcript() -> List[Dict[str, Any]]:+ """Cron shape whose LAST row is an assistant tool_calls turn still awaiting+ its result — compaction fired inside the tool-execution window."""+ msgs = _cron_transcript()+ msgs.append(+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {"id": "pending", "function": {"name": "terminal", "arguments": "{}"}}+ ],+ }+ )+ return msgs+++def test_pending_trailing_tool_call_survives_the_replay():+ """The replay row must not make a genuinely in-flight tool_call look+ orphaned: _sanitize_tool_pairs runs before the re-append, so the trailing+ assistant(tool_calls) keeps its calls and the late tool result still pairs."""+ out = _compress(_pending_tail_transcript())+ pending = [+ m+ for m in out+ if m.get("role") == "assistant"+ and any(tc.get("id") == "pending" for tc in (m.get("tool_calls") or []))+ ]+ assert pending, "trailing in-flight tool_calls were stripped"+ replay_idx = max(+ i for i, m in enumerate(out)+ if m.get("role") == "user" and JOB_SENTINEL in str(m.get("content"))+ )+ assert replay_idx > out.index(pending[0])+++def _compress_with(protect_first_n: int, compression_count: int, messages):+ response = MagicMock()+ response.choices = [MagicMock()]+ response.choices[0].message.content = SUMMARY_PREFIX + "\n## Summary\nran steps."+ with patch(+ "agent.context_compressor.get_model_context_length", return_value=100_000+ ):+ compressor = ContextCompressor(+ model="test",+ quiet_mode=True,+ protect_first_n=protect_first_n,+ protect_last_n=2,+ )+ compressor.tail_token_budget = 500+ compressor.compression_count = compression_count+ with patch.object(+ compressor, "_generate_summary", return_value=response.choices[0].message.content+ ):+ return compressor.compress(messages, current_tokens=90_000)+++def _job_copies(messages) -> int:+ return sum(+ str(m.get("content")).count(JOB_SENTINEL)+ for m in messages+ if m.get("role") == "user"+ )+++def test_merged_restatement_is_not_anchored_twice():+ """Later cycle: protect_first_n has decayed, the prompt is summarised away+ and the summary is pinned to role=user followed by an exempt tool tail, so+ the restatement is MERGED onto the carrier. The later+ _ensure_compressed_has_user_turn pass must see intent as present instead+ of inserting a second copy of the job prompt."""+ from agent.conversation_compression import _ensure_compressed_has_user_turn++ original = [{"role": "user", "content": JOB_SENTINEL}, *_tool_pairs(40)]+ out = _compress_with(2, 1, original)+ assert any(m.get("_inflight_replay_merged") for m in out), "expected merge layout"+ assert _job_copies(out) == 1+ assert _ensure_compressed_has_user_turn(original, out) == "already_present"+ assert _job_copies(out) == 1+++def test_restatement_survives_repeated_compactions_without_stacking():+ """A task alive across three compactions is restated exactly once per+ output — one copy, one header, always after the summary."""+ from agent.context_compressor import _INFLIGHT_TASK_REPLAY_HEADER++ out = [{"role": "user", "content": JOB_SENTINEL}, *_tool_pairs(40)]+ for cycle in (1, 2, 3):+ extra = _tool_pairs(40, start=100 * cycle) if cycle > 1 else []+ out = _compress_with(2, cycle, out + extra)+ users = [m for m in out if m.get("role") == "user"]+ assert _job_copies(out) == 1, cycle+ assert max(+ str(m.get("content")).count(_INFLIGHT_TASK_REPLAY_HEADER) for m in users+ ) == 1, cycle+ last = str(users[-1].get("content"))+ assert last.rfind(JOB_SENTINEL) > last.rfind(_SUMMARY_END_MARKER), cycle+++def test_flagged_scaffolding_row_is_never_the_inflight_task():+ """A trailing user-role scaffolding row flagged synthetic (todo snapshot)+ must not be mistaken for the live request and replayed as an instruction."""+ msgs = _cron_transcript()+ msgs.append(+ {+ "role": "user",+ "content": "[Your active task list was preserved across context compression]\n- x",+ "_todo_snapshot_synthetic": True,+ }+ )+ found = ContextCompressor._find_inflight_user_task(msgs)+ assert found is not None+ assert JOB_SENTINEL in str(found.get("content"))