From 8f42701f7a0334dab2e7bc7d5e2317bbc42b06dd Mon Sep 17 00:00:00 2001 From: raymondginger Date: Fri, 6 Nov 2026 22:31:16 +0800 Subject: [PATCH] feat(agent): carry the user's own earlier wording across compaction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The summary is lossy by design, and the one thing it should not be allowed to paraphrase away is what the user actually asked for. This carries the user's own earlier messages over the checkpoint boundary, quoted verbatim. Two things the first revision got wrong, both visible in a real session: - **It took "the first user message", which is the environment slot.** Every session with a workspace starts with `{"role": "user", "env_context": True}`, so the helper returned the environment dump. Measured on a real `AgentSession(workspace=…)` + `compact()`: a 6,363-character request was replaced by a 229-character environment dump, and the request itself was gone from the whole history. - **It kept up to 60,000 characters under a permanent "ORIGINAL TASK" label.** That both swamped the checkpoint and pinned the model to old work — in a multi-turn session the first message is often not what is being worked on. Now: the user's own earlier messages, newest first, under a few-thousand character budget, under a neutral heading ("Earlier messages from the user (most recent first):"). The environment slot, checkpoints and empty content are skipped; a message already in the kept tail is not repeated; a single oversized message is truncated to the budget rather than skipped. The block is also bounded by the space the compaction actually freed, minus a reserve for the runner's PreCompact checkpoint re-injection. Both draw on the same reduction, and an earlier revision consumed all of it: a neighbouring test showed the hook's context truncated to three characters. When there is not enough room the block is simply absent, which is exactly what main does. Re-compaction re-reads the block from the previous checkpoint, so a second round does not lose it. Runtime notes are not filtered by `is_context_note()`: by the time this runs the kernel history projection has already dropped user-role metadata, so no marker is left to test. The skip is shape-based, and the docstring says so. Tests: tests/test_session_compaction.py 13 passed; the neighbouring tests/test_session_end_lifecycle.py matches main exactly (4 pre-existing local failures, unchanged). New coverage pins newest-first ordering, the budget, env-slot/checkpoint skipping, the neutral heading, re-compaction carry-forward, and one end-to-end case that drives `AgentSession(workspace=…)` and `await session.compact()`. Two assertions this branch had added now restate main instead: they claimed "the original task (MSG0) survives", which is precisely the behaviour being removed. ruff 0.15.21 check and format clean. --- core/agent_runtime/compaction.py | 111 +++++++++++++++++++- tests/test_session_compaction.py | 171 ++++++++++++++++++++++++++++++- 2 files changed, 276 insertions(+), 6 deletions(-) diff --git a/core/agent_runtime/compaction.py b/core/agent_runtime/compaction.py index 7f4c7e9c3..4e8a0dd73 100644 --- a/core/agent_runtime/compaction.py +++ b/core/agent_runtime/compaction.py @@ -49,6 +49,22 @@ "messages it replaced, not as a report from someone else. Do not repeat " "work it says is done. Summary:" ) +# Heading for the block appended to the checkpoint AFTER the summary: the +# user's own earlier messages, newest first, quoted verbatim. Not labelled as +# "the original task" — in a multi-turn session the first message is often no +# longer the work in hand, and a permanent label pulls the model back to it. +# Appended after the prefix (never before) so ``SUMMARY_PREFIX`` keeps offset 0. +EARLIER_USER_LABEL = "Earlier messages from the user (most recent first):" +_EARLIER_USER_MARK = f"\n\n{EARLIER_USER_LABEL}\n" +# How much of the user's own earlier wording to carry. A few thousand +# characters: enough to keep the request that started the work, small enough +# that compaction still shrinks the history — the convergence rule refuses a +# "compaction" that does not. +EARLIER_USER_CHARS = 4_000 +# Room left for the runner's PreCompact checkpoint re-injection, which is bounded +# by the same reduction this block draws on. Without a reserve this block would +# consume it and the hook's context would be truncated to nothing. +_PRECOMPACT_RESERVE = 1_000 class CompactionStrategy(Protocol): @@ -92,6 +108,70 @@ def _unit_start(messages: list[dict[str, Any]], end: int) -> int: return index +def _earlier_user_messages( + non_system: list[dict[str, Any]], budget: int = EARLIER_USER_CHARS +) -> list[str]: + """The user's own earlier messages, newest first, within ``budget`` chars. + + Deliberately not "the original task". In a real session the first user + message is the environment slot (``env_context``), and in a multi-turn + session the first thing the user said is often not what is being worked on + any more — a Goal may have been set or updated since. Keeping the NEWEST + earlier messages under a small budget preserves the words that still point + at the current work; a permanent "original task" label would pull the model + back to old work instead. + + Skipped: the environment slot, compaction checkpoints, and empty content. + Runtime notes carry no marker by the time this runs (the kernel history + projection drops user-role metadata), so they can only be excluded here by + their shape, not by :func:`core.sessions.transcript.is_context_note`. + """ + picked: list[str] = [] + used = 0 + carried: list[str] = [] + + def add(text: str) -> bool: + """Take ``text`` if it fits; take a truncated head when nothing has yet.""" + nonlocal used + if used + len(text) <= budget: + picked.append(text) + used += len(text) + return True + if not picked and not carried: + # The newest message alone exceeds the budget. Carrying nothing + # would drop the user's current words entirely, so take the head. + picked.append(text[:budget]) + used = budget + return False + + for item in reversed(non_system): + if item.get("role") != "user": + continue + if item.get("env_context"): + continue + if item.get("compaction"): + # A checkpoint from an earlier round already carries the wording it + # kept; re-read it so a second compaction does not lose it. + block = str(item.get("content") or "") + at = block.rfind(_EARLIER_USER_MARK) + if at >= 0: + carried.extend( + text.strip() + for text in block[at + len(_EARLIER_USER_MARK) :].split("\n\n") + if text.strip() + ) + continue + text = str(item.get("content") or "").strip() + if not text: + continue + if not add(text) or used >= budget: + break + for text in carried: + if not add(text): + break + return picked + + class TailRetainingCompactionStrategy: """Head-anchored checkpoint plus a bounded recent tail. @@ -153,9 +233,38 @@ def build_history( kept = chunk + kept used += chunk_chars index = start - 1 + # Carry the user's own earlier wording across the checkpoint. The + # summary is lossy by design, and the one thing it should not be allowed + # to paraphrase away is what the user actually asked for. Newest first + # and bounded: see :func:`_earlier_user_messages`. Nothing is added when + # the kept tail already carries these messages verbatim. + checkpoint_content = f"{SUMMARY_PREFIX}\n{summary}" + # Carry the user's own earlier wording across the checkpoint, but only + # within the space the summary actually freed, and only after reserving + # room for the runner's PreCompact checkpoint re-injection -- that one is + # bounded by the same reduction, so eating it all would truncate the + # hook's context to nothing. A history that does not shrink enough + # carries nothing, which is what main does. + before = sum(message_chars(item) for item in messages) + base_after = ( + sum(message_chars(item) for item in system) + + len(checkpoint_content) + + sum(message_chars(item) for item in kept) + ) + headroom = before - base_after - len(_EARLIER_USER_MARK) - _PRECOMPACT_RESERVE + earlier = ( + _earlier_user_messages(non_system, budget=min(EARLIER_USER_CHARS, headroom)) + if headroom > 0 + else [] + ) + kept_texts = {str(item.get("content") or "") for item in kept} + earlier = [text for text in earlier if text not in kept_texts] + if earlier: + quoted = "\n\n".join(earlier) + checkpoint_content += _EARLIER_USER_MARK + quoted checkpoint = { "role": "user", - "content": f"{SUMMARY_PREFIX}\n{summary}", + "content": checkpoint_content, "compaction": {"reset": True, "retain": len(kept)}, } return system + [checkpoint] + kept diff --git a/tests/test_session_compaction.py b/tests/test_session_compaction.py index 2fc334210..71a3a8d40 100644 --- a/tests/test_session_compaction.py +++ b/tests/test_session_compaction.py @@ -80,7 +80,9 @@ def test_long_history_is_trimmed_before_the_model(): # Trimmed: strictly fewer than the 20 preloaded + 1 new user message. assert len(received) < 21 joined = " ".join(str(m.get("content")) for m in received) - # Newest turn survives; oldest is dropped. + # Newest turn survives; the old turns are replaced by the summary. The + # checkpoint carries the user's NEWEST earlier wording, so the oldest turn + # (MSG0) is genuinely gone rather than resurrected. assert "FINAL newest question" in joined assert "MSG0 " not in joined # The system prompt is always preserved at the head. @@ -104,7 +106,11 @@ def test_short_history_is_untouched(): # -- C4a: summarization-based compaction ------------------------------------ -from core.agent_runtime.compaction import SUMMARY_PREFIX as _SUMMARY_PREFIX # noqa: E402 +from core.agent_runtime.compaction import ( # noqa: E402 + EARLIER_USER_CHARS as _EARLIER_USER_CHARS, + EARLIER_USER_LABEL as _EARLIER_USER_LABEL, + SUMMARY_PREFIX as _SUMMARY_PREFIX, +) from core.agent_runtime.runner import ( # noqa: E402 AgentRunner, AgentRunSpec, @@ -118,7 +124,9 @@ def test_build_compacted_history_keeps_recent_tail_and_checkpoint(): messages = [ {"role": "system", "content": "sys"}, {"role": "user", "content": "u1"}, - {"role": "assistant", "content": "a1"}, + # Bulky on purpose: the block may only use the space the summary frees, + # so a toy history would legitimately carry nothing. + {"role": "assistant", "content": "a1 " + "x" * 3_000}, {"role": "user", "content": "u2"}, { "role": "assistant", @@ -130,7 +138,11 @@ def test_build_compacted_history_keeps_recent_tail_and_checkpoint(): ] out = AgentRunner._build_compacted_history(messages, "THE SUMMARY") assert out[0]["role"] == "system" - assert out[1]["content"] == f"{_SUMMARY_PREFIX}\nTHE SUMMARY" + # The dropped turn's user wording (u1) survives verbatim inside the + # checkpoint; u2 is already in the kept tail, so it is not repeated. + assert out[1]["content"] == ( + f"{_SUMMARY_PREFIX}\nTHE SUMMARY\n\n{_EARLIER_USER_LABEL}\nu1" + ) assert out[1].get("compaction", {}).get("reset") is True # The newest user turn and everything it produced survive verbatim. assert [m.get("role") for m in out[2:]] == [ @@ -142,7 +154,155 @@ def test_build_compacted_history_keeps_recent_tail_and_checkpoint(): assert any(m.get("content") == "a2" for m in out) assert any(m.get("role") == "tool" for m in out) # The older turn is what the checkpoint stands in for. - assert not any(m.get("content") in {"u1", "a1"} for m in out) + assert not any(m.get("content") == "u1" for m in out) + assert not any("x" * 3_000 in str(m.get("content") or "") for m in out) + + +def test_earlier_user_messages_are_newest_first_and_skip_noise(): + """Newest first, and never the environment slot or a checkpoint.""" + from core.agent_runtime.compaction import _earlier_user_messages + + non_system = [ + {"role": "user", "content": "", "env_context": True}, + {"role": "user", "content": "u1 the first ask"}, + {"role": "assistant", "content": "a1"}, + {"role": "user", "content": "u2"}, + {"role": "assistant", "content": "a2"}, + { + "role": "user", + "content": "summary of everything", + "compaction": {"reset": True, "retain": 0}, + }, + {"role": "assistant", "content": "a3"}, + {"role": "user", "content": "u3 the current ask"}, + ] + assert _earlier_user_messages(non_system) == [ + "u3 the current ask", + "u2", + "u1 the first ask", + ] + + +def test_earlier_user_messages_stop_at_the_budget(): + """A budget keeps the newest wording and refuses to grow with history.""" + from core.agent_runtime.compaction import _earlier_user_messages + + non_system = [{"role": "user", "content": f"m{i} " + "x" * 40} for i in range(6)] + picked = _earlier_user_messages(non_system, budget=100) + assert len(picked) == 2, picked # 45 chars each, 100 budget + assert picked[0].startswith("m5") # newest first + assert picked[1].startswith("m4") + + +def test_checkpoint_carries_the_users_earlier_wording(): + """The user's own words survive compaction, under a neutral heading.""" + ask = "please refactor the widget pipeline end to end" + messages = [ + {"role": "system", "content": "sys"}, + {"role": "user", "content": ask}, + # Bulky on purpose: the block may only use the space the summary frees. + {"role": "assistant", "content": "a1 " + "x" * 3_000}, + {"role": "user", "content": "u2"}, + {"role": "assistant", "content": "a2"}, + ] + out = AgentRunner._build_compacted_history(messages, "THE SUMMARY") + assert out[1]["content"] == ( + f"{_SUMMARY_PREFIX}\nTHE SUMMARY\n\n{_EARLIER_USER_LABEL}\n{ask}" + ) + # Not called "the original task": that label pulls the model back to old work. + assert "ORIGINAL TASK" not in out[1]["content"] + assert out[1]["compaction"] == {"reset": True, "retain": 2} + + +def test_checkpoint_never_carries_more_than_the_earlier_user_budget(): + """A huge first message cannot swamp the checkpoint.""" + ask = "T" * 70_000 + messages = [ + {"role": "system", "content": "sys"}, + {"role": "user", "content": ask}, + {"role": "assistant", "content": "a1"}, + {"role": "user", "content": "u2"}, + {"role": "assistant", "content": "a2"}, + ] + out = AgentRunner._build_compacted_history(messages, "THE SUMMARY") + content = out[1]["content"] + assert len(content) < _EARLIER_USER_CHARS + 1_000 + assert ask not in content + + +def test_recompaction_keeps_carrying_the_user_wording(): + """A checkpoint's own block is re-read, not lost on the next round.""" + from core.agent_runtime.compaction import _earlier_user_messages + + ask = "please refactor the widget pipeline end to end" + checkpoint = { + "role": "user", + "content": (f"{_SUMMARY_PREFIX}\nSUMMARY 1\n\n{_EARLIER_USER_LABEL}\n{ask}"), + "compaction": {"reset": True, "retain": 0}, + } + assert _earlier_user_messages([checkpoint]) == [ask] + + +class _TurnOrSummaryProvider: + """Real turns answer 'ok'; the summarization request gets a handoff.""" + + def __init__(self) -> None: + self.turns = 0 + self.summaries = 0 + + def get_default_model(self) -> str: + return "fake-model" + + async def chat_with_retry(self, **kwargs: Any) -> LLMResponse: + messages = kwargs.get("messages") or [] + joined = " ".join(str(m.get("content") or "") for m in messages) + if "CONTEXT CHECKPOINT COMPACTION" in joined: + self.summaries += 1 + return LLMResponse(content="HANDOFF: did X", finish_reason="stop") + self.turns += 1 + return LLMResponse(content="ok", finish_reason="stop") + + +def test_compaction_in_a_workspace_session_skips_the_environment_slot(tmp_path): + """The app path: a workspace prepends an env slot that must not be carried. + + This is the case the unit-level shapes miss: in a real session every history + starts with ``{"role": "user", "env_context": True}``, so "the first user + message" is the environment, not the request. It also has to stay bounded: + a large first message must not ride into every later checkpoint. + """ + + async def scenario() -> None: + workspace = tmp_path / "repo" + workspace.mkdir() + provider = _TurnOrSummaryProvider() + session = AgentSession( + provider, ToolRegistry(), model="fake-model", workspace=workspace + ) + task = ( + "REFACTOR-THE-PIPELINE: stream it, keep bytes identical " + "-detail" * 900 + ) + await session.submit(UserInput(text=task)) + session.drain_events() + for i in range(5): + await session.submit(UserInput(text=f"follow-up {i}: " + "y" * 300)) + session.drain_events() + + # Sanity: the workspace put an environment slot at the head of history. + assert session.history[0].get("env_context") is True + + await session.compact() + + checkpoint = next(m for m in session.history if m.get("compaction")) + content = str(checkpoint.get("content") or "") + assert provider.summaries == 1 + assert "environment_context" not in content + assert "ORIGINAL TASK" not in content + assert len(content) < _EARLIER_USER_CHARS + 2_000 + # The user's own recent wording is what the block carries. + assert "follow-up" in content + + asyncio.run(scenario()) class _CompactProvider: @@ -213,6 +373,7 @@ def test_over_budget_history_is_summarized_not_just_dropped(): assert _SUMMARY_PREFIX in joined and "HANDOFF: did X" in joined assert "FINAL question" in joined assert "MSG0 " not in joined # old turns replaced by the summary + assert "MSG1 " not in joined assert result.final_content == "done" assert result.usage == { "prompt_tokens": 150,