The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(agent): cover reference-only handoff sole-active-turn regression
HexLab98b9636b1047c4
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.pyindex 0292bf51a25..4c56e585aad 100644--- a/tests/agent/test_micro_compaction.py+++ b/tests/agent/test_micro_compaction.py@@ -451,8 +451,9 @@ class TestMicroCompaction:def test_first_pass_costs_marker_overhead_then_pays_it_back(self):"""The first pass can grow the transcript; later passes recover it.- Inserting the summary marker costs a fixed ~400 tokens of scaffolding- (the compaction preamble, the historical heading and the end marker).+ Inserting the summary marker costs a fixed block of scaffolding+ (``SUMMARY_PREFIX``, the historical heading and the end marker —+ currently ~450 tokens and grows when the preamble is lengthened).On pass one that overhead is paid against a single absorbed exchange,so the net can be positive. From pass two on the marker is replacedrather than added, so the scaffolding is already paid for and each@@ -476,13 +477,20 @@ class TestMicroCompaction:assert after_many < after_first, "later passes must recover it"def test_cumulative_savings_accumulate_across_passes(self):+ """Session-total savings go positive once marker overhead is paid back.++ The first pass inserts ``SUMMARY_PREFIX`` scaffolding (~450 tokens);+ with the current preamble that alone leaves the cumulative counter+ negative after only a few absorptions. Enough later passes must+ still recover it — that is the amortization contract.+ """cc = _compressor()messages = _conversation(exchanges=10)- for _ in range(4):+ for _ in range(6):messages = cc._micro_compact(messages)- assert cc._micro_compact_passes == 4+ assert cc._micro_compact_passes == 6assert cc._micro_compact_tokens_saved_total > 0def test_defrag_triggers_once_the_rolling_summary_grows(self):diff --git a/tests/agent/test_reference_handoff_active_turn.py b/tests/agent/test_reference_handoff_active_turn.pynew file mode 100644index 00000000000..4e62b0f9b83--- /dev/null+++ b/tests/agent/test_reference_handoff_active_turn.py@@ -0,0 +1,184 @@+"""Regression coverage for #80622: a reference-only compaction handoff must+never become the active user turn after a completed assistant response.++Failure mode (real report): assistant finished with ``finish_reason=stop``,+Hermes inserted a standalone ``role=user`` ``[CONTEXT COMPACTION — REFERENCE+ONLY]`` handoff containing a Historical Task Snapshot, no new human request+followed, and the agent immediately started a tool-calling turn that resumed+the already-completed work.+"""++from __future__ import annotations++from agent.context_compressor import (+ COMPRESSED_SUMMARY_HAS_USER_TURN_KEY,+ COMPRESSED_SUMMARY_METADATA_KEY,+ COMPRESSION_CONTINUATION_USER_CONTENT,+ HISTORICAL_TASK_HEADING,+ SUMMARY_PREFIX,+ _SUMMARY_END_MARKER,+ is_compaction_summary_message,+ is_user_originated_turn,+ reference_handoff_would_drive_next_model_call,+)+from agent.conversation_loop import (+ _should_skip_model_call_for_reference_handoff,+)+from agent.turn_context import reanchor_current_turn_user_idx+++def _standalone_handoff(task: str = "finish the already-done refactor") -> dict:+ return {+ "role": "user",+ "content": (+ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\n"+ f"User asked: '{task}'\n\n{_SUMMARY_END_MARKER}"+ ),+ COMPRESSED_SUMMARY_METADATA_KEY: True,+ COMPRESSED_SUMMARY_HAS_USER_TURN_KEY: True,+ }+++class TestReferenceHandoffWouldDriveNextModelCall:+ def test_standalone_handoff_alone_drives(self):+ messages = [_standalone_handoff()]+ assert reference_handoff_would_drive_next_model_call(messages) is True++ def test_handoff_after_completed_stop_drives(self):+ """The reported sequence: assistant stop, then synthetic handoff."""+ messages = [+ {"role": "user", "content": "please finish the refactor"},+ {+ "role": "assistant",+ "content": "Refactor complete.",+ "finish_reason": "stop",+ },+ _standalone_handoff(),+ ]+ assert reference_handoff_would_drive_next_model_call(messages) is True++ def test_real_user_after_handoff_does_not_drive(self):+ messages = [+ _standalone_handoff(),+ {"role": "user", "content": "what's the capital of France?"},+ ]+ assert reference_handoff_would_drive_next_model_call(messages) is False++ def test_mid_tool_loop_after_handoff_does_not_drive(self):+ messages = [+ _standalone_handoff(),+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "terminal"}}],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "ok"},+ ]+ assert reference_handoff_would_drive_next_model_call(messages) is False++ def test_embedded_remainder_after_end_marker_does_not_drive(self):+ messages = [+ {+ "role": "user",+ "content": (+ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold\n\n"+ f"{_SUMMARY_END_MARKER}\n\nwhat's the capital of France?"+ ),+ COMPRESSED_SUMMARY_METADATA_KEY: True,+ }+ ]+ assert reference_handoff_would_drive_next_model_call(messages) is False++ def test_continuation_marker_alone_still_drives(self):+ """Synthetic continuation is not a human ask — sole-handoff ++ continuation must not license a fresh tool loop after stop."""+ messages = [+ _standalone_handoff(),+ {"role": "user", "content": COMPRESSION_CONTINUATION_USER_CONTENT},+ ]+ assert reference_handoff_would_drive_next_model_call(messages) is True+++class TestSkipGuardRestoresRealUser:+ def test_restores_pending_user_then_allows_continue(self):+ messages = [+ {+ "role": "assistant",+ "content": "done",+ "finish_reason": "stop",+ },+ _standalone_handoff(),+ ]+ assert _should_skip_model_call_for_reference_handoff(+ messages, "new ask after compaction"+ ) is False+ assert messages[-1]["role"] == "user"+ assert messages[-1]["content"] == "new ask after compaction"++ def test_skips_when_no_real_user_to_restore(self):+ messages = [+ {+ "role": "assistant",+ "content": "Refactor complete.",+ "finish_reason": "stop",+ },+ _standalone_handoff(),+ ]+ assert _should_skip_model_call_for_reference_handoff(messages, None) is True+++class TestUserOriginatedTurnPredicate:+ def test_standalone_handoff_not_user_originated_even_with_has_user_turn(self):+ handoff = _standalone_handoff()+ assert is_compaction_summary_message(handoff) is True+ assert is_user_originated_turn(handoff) is False++ def test_plain_user_is_originated(self):+ assert is_user_originated_turn({"role": "user", "content": "hello"}) is True++ def test_display_kind_hidden_not_originated(self):+ assert (+ is_user_originated_turn(+ {+ "role": "user",+ "content": "opaque",+ "display_kind": "hidden",+ }+ )+ is False+ )+++class TestReanchorSkipsHandoffFallback:+ def test_fallback_skips_standalone_handoff(self):+ messages = [+ {"role": "system", "content": "sys"},+ _standalone_handoff(),+ ]+ assert reanchor_current_turn_user_idx(messages, "missing ask") == -1++ def test_exact_match_still_wins(self):+ messages = [+ _standalone_handoff(),+ {"role": "user", "content": "live ask"},+ ]+ assert reanchor_current_turn_user_idx(messages, "live ask") == 1++ def test_fallback_prefers_real_user_over_handoff(self):+ messages = [+ {"role": "user", "content": "original ask"},+ _standalone_handoff(),+ ]+ # Exact content rewritten by merge — fall back must not land on handoff.+ assert reanchor_current_turn_user_idx(messages, "rewritten ask") == 0+++class TestNoToolCallsWithoutLaterRealUser:+ def test_historical_snapshot_alone_is_not_actionable(self):+ """Suggested regression #3: executable-looking snapshot must not+ count as a user-originated turn."""+ handoff = _standalone_handoff(+ "run npm test and fix every failure in the suite"+ )+ assert is_user_originated_turn(handoff) is False+ assert reference_handoff_would_drive_next_model_call([handoff]) is Truediff --git a/tests/agent/test_resume_stale_active_task.py b/tests/agent/test_resume_stale_active_task.pyindex 5820e7b0494..9b224f43c3c 100644--- a/tests/agent/test_resume_stale_active_task.py+++ b/tests/agent/test_resume_stale_active_task.py@@ -60,6 +60,8 @@ def test_latest_message_wins_over_inherited_active_task():# resumption on topic overlap (#41607, #38364) — it must stay gone.assert "you may use the summary as background" not in lowerassert "topic overlap" in lower+ # #80622: empty-after-handoff must not resume historical work.+ assert "if no user message appears after this summary" in lowerdiff --git a/tests/agent/test_summary_prefix_semantics.py b/tests/agent/test_summary_prefix_semantics.pyindex 4e466308e5c..4af2ec80084 100644--- a/tests/agent/test_summary_prefix_semantics.py+++ b/tests/agent/test_summary_prefix_semantics.py@@ -75,6 +75,35 @@ def test_replaced_prefixes_are_frozen_for_renormalization():# derive them from module constants — the tests below must fail if any# frozen entry is mutated, reordered, or dropped._FROZEN_PREFIX_GENERATIONS = (+ # Pre-#80622: tools-active + topic-overlap discard, but no+ # "if no user message appears AFTER this summary, do nothing" clause.+ (+ "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were "+ "compacted into the summary below. This is a handoff from a "+ "previous context window — treat it as background reference, NOT "+ "as active instructions. Do NOT answer questions or fulfill "+ "requests mentioned in this summary; they were already addressed. "+ "Respond ONLY to the latest user message that appears AFTER this "+ "summary — that message is the single source of truth for what to "+ "do right now. Topic overlap with the summary does NOT mean you "+ "should resume its task: even on similar topics, the latest user "+ "message WINS. Treat ONLY the latest message as the active task "+ "and discard stale items from '## Historical Task Snapshot' "+ "entirely — do not 'wrap up' or 'finish' work described there "+ "unless the latest message explicitly asks for it. Reverse "+ "signals in the latest message (e.g. 'stop', 'undo', 'roll "+ "back', 'just verify', 'don't do that anymore', 'never mind', a "+ "new topic) must immediately end any in-flight work described in "+ "the summary; do not re-surface it in later turns. IMPORTANT: "+ "Your persistent memory (MEMORY.md, USER.md) in the system "+ "prompt is ALWAYS authoritative and active — never ignore or "+ "deprioritize memory content due to this compaction note. None "+ "of the above restricts HOW you work: your tools remain fully "+ "active — keep calling them normally for the active task (edit "+ "files, run commands, search) instead of merely narrating what "+ "you would do. The current session state (files, config, etc.) "+ "may reflect work described here — avoid repeating it:"+ ),# Pre-#69619: four-heading discard clause + tools-active clause.("[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were "@@ -174,8 +203,18 @@ _FROZEN_PREFIX_GENERATIONS = (# The generation retired by #69619, pinned individually for the review-# regression below.-_PRE_69619_LIVE_PREFIX = _FROZEN_PREFIX_GENERATIONS[0]+# regression below. Index 1 after the #80622 freeze was prepended.+_PRE_69619_LIVE_PREFIX = _FROZEN_PREFIX_GENERATIONS[1]+++def test_no_user_after_handoff_must_not_act():+ """#80622: a reference-only handoff with nothing after it must not+ resume historical work or call tools."""+ lower = SUMMARY_PREFIX.lower()+ assert "if no user message appears after this summary" in lower+ assert "do nothing" in lower+ assert "wait for a new user message" in lower+ assert "must never become the active turn" in lowerdef test_pre_69619_prefix_generation_is_frozen_and_stripped():@@ -199,3 +238,13 @@ def test_pre_69619_prefix_generation_is_frozen_and_stripped():assert ContextCompressor._strip_summary_prefix(content) == "BODY"+def test_frozen_prefix_generations_match_historical_tuple():+ """Every retired generation must stay byte-identical in+ _HISTORICAL_SUMMARY_PREFIXES (newest-first)."""+ from agent.context_compressor import _HISTORICAL_SUMMARY_PREFIXES++ assert tuple(_HISTORICAL_SUMMARY_PREFIXES[: len(_FROZEN_PREFIX_GENERATIONS)]) == (+ _FROZEN_PREFIX_GENERATIONS+ )++