Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): fold every compacted message through the summarizer

Haozhe Wudb164b9f8b92
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 6c856e813..15181811c 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -61,6 +61,7 @@ COLLAPSE_HEAD = 900
COLLAPSE_TAIL = 500
TAIL_TOKEN_BUDGET = 20_000
+SUMMARY_CHUNK_CHARS = 80_000
def _override(name: str):
@@ -224,6 +225,83 @@ def estimate_tokens(messages: list) -> int:
return len(json.dumps(messages, default=str, ensure_ascii=False)) // 4
+def _summary_chunks(msgs: list, limit: int = SUMMARY_CHUNK_CHARS) -> list[str]:
+ """Serialize messages into bounded chunks for lossless summary folding.
+
+ Messages are packed by whole-message boundaries so that ordinary chunks
+ remain valid JSON arrays and a summary call never receives a message that
+ was silently cut off. A single oversized message is split into explicitly
+ labeled raw-JSON fragments instead: the label tells the summarizer that a
+ fragment is not valid JSON by itself, while retaining every character
+ instead of dropping or silently truncating part of the conversation.
+
+ Args:
+ msgs: Messages to serialize and divide into chunks.
+ limit: Maximum number of characters allowed in each returned chunk.
+
+ Returns:
+ JSON-array strings, or labeled raw-JSON fragments for an oversized
+ message, each no longer than ``limit`` characters.
+
+ Raises:
+ ValueError: If ``limit`` cannot accommodate an empty JSON array or an
+ oversized-message fragment label.
+ """
+ if limit < 2:
+ raise ValueError("summary chunk limit must be at least 2 characters")
+
+ serialized = [json.dumps(msg, default=str, ensure_ascii=False) for msg in msgs]
+ chunks: list[str] = []
+ current: list[str] = []
+ current_len = 2 # The opening and closing brackets.
+
+ def flush_current() -> None:
+ nonlocal current, current_len
+ if current:
+ chunks.append("[" + ", ".join(current) + "]")
+ current = []
+ current_len = 2
+
+ for part in serialized:
+ # The two brackets are part of the chunk, so a message that only fits
+ # below ``limit`` as a raw JSON string may still need fragmentation.
+ if len(part) + 2 <= limit:
+ projected_len = current_len + len(part) + (2 if current else 0)
+ if current and projected_len > limit:
+ flush_current()
+ current.append(part)
+ current_len += len(part) + (2 if len(current) > 1 else 0)
+ continue
+
+ flush_current()
+
+ def fragment_prefix(index: int, total: int) -> str:
+ return (
+ f"[fragment {index}/{total} of one oversized message — "
+ "raw JSON slice, not valid JSON on its own]\n"
+ )
+
+ total = 1
+ while True:
+ capacity = limit - len(fragment_prefix(total, total))
+ if capacity <= 0:
+ raise ValueError(
+ "summary chunk limit is too small for an oversized-message label"
+ )
+ needed = max(1, (len(part) + capacity - 1) // capacity)
+ if needed <= total:
+ break
+ total = needed
+
+ for index in range(1, total + 1):
+ prefix = fragment_prefix(index, total)
+ start = (index - 1) * capacity
+ chunks.append(prefix + part[start : start + capacity])
+
+ flush_current()
+ return chunks or ["[]"]
+
+
def _microcompact(messages: list) -> None:
"""Layer 1: silently prune old tool results, keeping the most recent N intact.
@@ -1859,20 +1937,28 @@ class AgentLoop:
# Build focus section
focus_section = _FOCUS_SECTION.format(topic=focus_topic) if focus_topic else ""
- # Build summary prompt (structured template or iterative update)
- conv_text = json.dumps(head, default=str, ensure_ascii=False)[:80000]
-
- if self._previous_summary:
- prompt = _ITERATIVE_UPDATE_PROMPT.format(
- previous_summary=self._previous_summary,
- new_turns=conv_text,
- focus_section=focus_section,
- )
- else:
- prompt = _STRUCTURED_SUMMARY_PROMPT.format(focus_section=focus_section) + conv_text
+ # Fold every head chunk so no message falls between the summary prompt
+ # and the preserved tail. The first fresh chunk gets the full
+ # structured handoff; subsequent chunks incrementally update it.
+ chunks = _summary_chunks(head)
+ logger.info("Auto compact: folding %d summary chunks", len(chunks))
+ summary = self._previous_summary or ""
+ for conv_text in chunks:
+ # Structured template while there is still nothing to update — that
+ # covers a fresh session's first chunk and the corner case where
+ # every fold so far returned empty content.
+ if not summary:
+ prompt = _STRUCTURED_SUMMARY_PROMPT.format(focus_section=focus_section) + conv_text
+ else:
+ prompt = _ITERATIVE_UPDATE_PROMPT.format(
+ previous_summary=summary,
+ new_turns=conv_text,
+ focus_section=focus_section,
+ )
- summary_resp = self.llm.chat([{"role": "user", "content": prompt}])
- summary = summary_resp.content or ""
+ summary_resp = self.llm.chat([{"role": "user", "content": prompt}])
+ if summary_resp.content:
+ summary = summary_resp.content
self._previous_summary = summary
tokens_before = estimate_tokens(messages)
@@ -1882,6 +1968,7 @@ class AgentLoop:
"iter": iteration,
"tokens_before": tokens_before,
"focus_topic": focus_topic or "(none)",
+ "summary_chunks": len(chunks),
},
field="summary",
value=summary,
diff --git a/agent/tests/test_auto_compact_chunked_summary.py b/agent/tests/test_auto_compact_chunked_summary.py
new file mode 100644
index 000000000..eaec242d4
--- /dev/null
+++ b/agent/tests/test_auto_compact_chunked_summary.py
@@ -0,0 +1,129 @@
+"""Regression tests for lossless, chunked auto-compaction summaries."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+from src.agent.loop import AgentLoop, _summary_chunks
+from src.agent.tools import ToolRegistry
+from src.agent.trace import TraceWriter
+
+
+class _CompactionLLM:
+ """Stub LLM that records compaction prompts and returns queued summaries."""
+
+ def __init__(self, responses: list[str]) -> None:
+ self.responses = list(responses)
+ self.prompts: list[str] = []
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> Any:
+ self.prompts.append(messages[0]["content"])
+ return SimpleNamespace(content=self.responses.pop(0))
+
+
+def _build_agent(llm: Any) -> AgentLoop:
+ """Build an AgentLoop with the same lightweight registry pattern as loop tests."""
+ return AgentLoop(registry=ToolRegistry(), llm=llm, max_iterations=1)
+
+
+def test_summary_chunks_single_chunk_matches_json_dumps() -> None:
+ """The common one-chunk path must preserve the original prompt bytes."""
+ messages = [
+ {"role": "user", "content": "请保留 unicode、emoji 🚀 和 punctuation"},
+ {"role": "assistant", "content": "ack", "metadata": {"n": 1}},
+ ]
+
+ chunks = _summary_chunks(messages)
+
+ assert len(chunks) == 1
+ assert chunks[0] == json.dumps(messages, default=str, ensure_ascii=False)
+
+
+def test_summary_chunks_cover_every_message_at_message_boundaries() -> None:
+ """Multiple ordinary chunks contain every whole message exactly once."""
+ messages = [
+ {
+ "role": "user",
+ "content": f"__CHUNK_MESSAGE_{index}__ " + ("x" * 80),
+ }
+ for index in range(5)
+ ]
+
+ chunks = _summary_chunks(messages, limit=220)
+
+ assert len(chunks) >= 3
+ assert all(len(chunk) <= 220 for chunk in chunks)
+ for index in range(5):
+ marker = f"__CHUNK_MESSAGE_{index}__"
+ assert sum(chunk.count(marker) for chunk in chunks) == 1
+ decoded = [message for chunk in chunks for message in json.loads(chunk)]
+ assert decoded == messages
+
+
+def test_summary_chunks_preserve_oversized_message_as_labeled_fragments() -> None:
+ """Fragment bodies concatenate back to the exact oversized raw JSON."""
+ message = {"role": "user", "content": "__OVERSIZED__" + ("z" * 500)}
+ raw = json.dumps(message, default=str, ensure_ascii=False)
+
+ chunks = _summary_chunks([message], limit=180)
+
+ assert len(chunks) > 1
+ assert all(len(chunk) <= 180 for chunk in chunks)
+ fragments: list[str] = []
+ for index, chunk in enumerate(chunks, start=1):
+ prefix, fragment = chunk.split("\n", 1)
+ assert f"fragment {index}/{len(chunks)}" in prefix
+ assert "raw JSON slice, not valid JSON on its own" in prefix
+ fragments.append(fragment)
+ assert "".join(fragments) == raw
+
+
+def test_auto_compact_folds_all_head_chunks_and_preserves_empty_update(
+ tmp_path: Path,
+) -> None:
+ """Every head marker reaches a summary call and empty updates keep state."""
+ markers = [f"__HEAD_MESSAGE_{index:02d}__" for index in range(6)]
+ head_messages = [
+ {
+ "role": "user",
+ "content": marker + " " + ("x" * 29_900),
+ }
+ for marker in markers
+ ]
+ # These two messages occupy the token-budget tail; all markers are in the
+ # six-message head and therefore must reach the folding calls.
+ tail_messages = [
+ {"role": "user", "content": "tail filler " + ("t" * 29_900)},
+ {"role": "assistant", "content": "tail filler " + ("u" * 29_900)},
+ ]
+ messages = [{"role": "system", "content": "system prompt"}, *head_messages, *tail_messages]
+ llm = _CompactionLLM(["summary-0", "", "summary-2"])
+ agent = _build_agent(llm)
+ trace = TraceWriter(tmp_path / "trace")
+
+ try:
+ agent._auto_compact(messages, tmp_path / "run", trace, iteration=7)
+ finally:
+ trace.close()
+
+ assert len(llm.prompts) == 3
+ assert "Summarize this conversation for handoff" in llm.prompts[0]
+ assert llm.prompts[1].startswith("Update the existing summary")
+ assert llm.prompts[2].startswith("Update the existing summary")
+ assert "summary-0" in llm.prompts[1]
+ # The second response was empty; its predecessor must still be supplied to
+ # the third fold and remain available after compaction.
+ assert "summary-0" in llm.prompts[2]
+ assert agent._previous_summary == "summary-2"
+
+ for marker in markers:
+ assert sum(prompt.count(marker) for prompt in llm.prompts) == 1
+
+ compact_entries = [
+ entry for entry in TraceWriter.read(tmp_path / "trace") if entry.get("type") == "compact"
+ ]
+ assert len(compact_entries) == 1
+ assert compact_entries[0]["summary_chunks"] == len(llm.prompts)