The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): collapse duplicate task sections during snapshot grounding
teknium1dbf19a6cfa6d
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 0de94ee662b..e2750fc09d2 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -3911,7 +3911,18 @@ Write only the summary body. Do not include any preamble or prefix."""# this regex on the next compaction (deleting every following section).replacement = f"{HISTORICAL_TASK_HEADING}\n{snapshot}\n\n"if _HISTORICAL_TASK_SECTION_RE.search(body):- return _HISTORICAL_TASK_SECTION_RE.sub(lambda _m: replacement, body, count=1).strip()+ # Replace the first task section and drop every later one: a summarizer that emits both the+ # canonical heading and the legacy alias would otherwise leave a second, undisclaimed task section.+ seen = False++ def _collapse(_m: re.Match) -> str:+ nonlocal seen+ if seen:+ return ""+ seen = True+ return replacement++ return _HISTORICAL_TASK_SECTION_RE.sub(_collapse, body).strip()return f"{replacement}{body}".strip()@classmethoddiff --git a/tests/agent/test_context_compressor_task_heading.py b/tests/agent/test_context_compressor_task_heading.pyindex 247d247716b..eacc4c7c823 100644--- a/tests/agent/test_context_compressor_task_heading.py+++ b/tests/agent/test_context_compressor_task_heading.py@@ -1,16 +1,23 @@-"""The iterative-update instruction must name the heading the template emits."""+"""Task-snapshot heading identity across the summarizer prompt, the template, and grounding.++The iterative-update instruction, the emitted template, and ``_ground_historical_task_snapshot`` must agree on+one heading. A leftover ``## Active Task`` section is not disclaimed by SUMMARY_PREFIX and reads as live work,+so grounding must replace it (and any duplicate task section) rather than prepend a second one.+"""from types import SimpleNamespace-from agent.context_compressor import (- ContextCompressor,- HISTORICAL_TASK_HEADING,- _HISTORICAL_TASK_SECTION_RE,-)+from agent.context_compressor import ContextCompressor, HISTORICAL_TASK_HEADING++_LEGACY_ACTIVE_TASK_HEADING = "## Active Task"++def _headings(text: str) -> list[str]:+ return [line for line in text.splitlines() if line.startswith("## ")]-def _iterative_prompt() -> str:- """The prompt built when a previous summary exists (the update path)."""++def test_update_instruction_names_the_emitted_heading():+ """The prompt built when a previous summary exists (the update path) names HISTORICAL_TASK_HEADING."""stub = SimpleNamespace(tail_mode="lean",_previous_summary="PREVIOUS SUMMARY BODY",@@ -18,23 +25,27 @@ def _iterative_prompt() -> str:)stub._summary_template_sections = ContextCompressor._summary_template_sectionsstub._build_summary_prompt = ContextCompressor._build_summary_prompt.__get__(stub)- return stub._build_summary_prompt("NEW TURNS", 2000, None, "", True)+ prompt = stub._build_summary_prompt("NEW TURNS", 2000, None, "", True)--def test_update_instruction_names_the_emitted_heading():- prompt = _iterative_prompt()assert f'Update "{HISTORICAL_TASK_HEADING}"' in prompt- assert '"## Active Task"' not in prompt-+ assert f'"{_LEGACY_ACTIVE_TASK_HEADING}"' not in prompt-def test_grounding_prepends_when_the_task_heading_differs():- """Why the names must agree: a foreign heading yields two task sections."""- body = "## Active Task\nUser asked: 'do X'\n\n## Goal\nthing\n"- assert _HISTORICAL_TASK_SECTION_RE.search(body) is None+def test_grounding_collapses_alias_and_duplicate_task_sections():+ """A summarizer that emits the legacy alias, or both headings, ends up with exactly one grounded section."""+ body = (+ f"{HISTORICAL_TASK_HEADING}\nUser asked: 'stale canonical'\n\n"+ "## Goal\nthing\n\n"+ f"{_LEGACY_ACTIVE_TASK_HEADING}\nUser asked: 'stale alias'\n\n"+ "## Constraints & Preferences\n- none\n"+ )grounded = ContextCompressor._ground_historical_task_snapshot.__func__(- ContextCompressor, body, [{"role": "user", "content": "do X"}]+ ContextCompressor, body, [{"role": "user", "content": "fresh ask"}])- headings = [line for line in grounded.splitlines() if line.startswith("## ")]++ headings = _headings(grounded)assert headings.count(HISTORICAL_TASK_HEADING) == 1- assert "## Active Task" in headings+ assert _LEGACY_ACTIVE_TASK_HEADING not in headings+ assert headings[1:] == ["## Goal", "## Constraints & Preferences"]+ assert "fresh ask" in grounded+ assert "stale" not in groundeddiff --git a/tests/agent/test_task_snapshot_heading_contract.py b/tests/agent/test_task_snapshot_heading_contract.pydeleted file mode 100644index e4967db02cd..00000000000--- a/tests/agent/test_task_snapshot_heading_contract.py+++ /dev/null@@ -1,73 +0,0 @@-"""Task-snapshot heading identity across prompt, template, and grounding.--The iterative summarizer prompt, the emitted template, and deterministic-grounding must share one heading. A leftover ``## Active Task`` section is-not disclaimed by SUMMARY_PREFIX and reads as live work (#114479 / #44454).-"""--from types import SimpleNamespace--from agent.context_compressor import (- ContextCompressor,- HISTORICAL_TASK_HEADING,-)--_LEGACY_ACTIVE_TASK_HEADING = "## Active Task"---def _iterative_update_prompt() -> str:- stub = SimpleNamespace(- tail_mode="lean",- _previous_summary="PREVIOUS SUMMARY BODY",- _bound_summary_input=lambda text: text,- )- stub._summary_template_sections = ContextCompressor._summary_template_sections- stub._build_summary_prompt = ContextCompressor._build_summary_prompt.__get__(stub)- return stub._build_summary_prompt("NEW TURNS", 2000, None, "", True)---def _headings(text: str) -> list[str]:- return [line for line in text.splitlines() if line.startswith("## ")]---def test_iterative_update_instruction_names_canonical_heading():- prompt = _iterative_update_prompt()- assert f'Update "{HISTORICAL_TASK_HEADING}"' in prompt- assert f'Update "{_LEGACY_ACTIVE_TASK_HEADING}"' not in prompt- assert HISTORICAL_TASK_HEADING in prompt---def test_grounding_replaces_legacy_active_task_heading():- body = (- f"{_LEGACY_ACTIVE_TASK_HEADING}\n"- "User asked: 'do X'\n\n"- "## Goal\n"- "thing\n"- )- grounded = ContextCompressor._ground_historical_task_snapshot.__func__(- ContextCompressor,- body,- [{"role": "user", "content": "do X"}],- )- headings = _headings(grounded)- assert headings.count(HISTORICAL_TASK_HEADING) == 1- assert _LEGACY_ACTIVE_TASK_HEADING not in headings- assert "## Goal" in headings---def test_grounding_keeps_single_canonical_heading():- body = (- f"{HISTORICAL_TASK_HEADING}\n"- "User asked: 'stale'\n\n"- "## Goal\n"- "thing\n"- )- grounded = ContextCompressor._ground_historical_task_snapshot.__func__(- ContextCompressor,- body,- [{"role": "user", "content": "fresh ask"}],- )- headings = _headings(grounded)- assert headings.count(HISTORICAL_TASK_HEADING) == 1- assert _LEGACY_ACTIVE_TASK_HEADING not in headings- assert "fresh ask" in grounded