Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(compaction): preserve real prior context across fallback chains

xf gong8f5b0a4721d1
diff --git a/cubepi/middleware/compaction/summarizer.py b/cubepi/middleware/compaction/summarizer.py
index b1e9855..74fe7c4 100644
--- a/cubepi/middleware/compaction/summarizer.py
+++ b/cubepi/middleware/compaction/summarizer.py
@@ -241,37 +241,61 @@ async def summarize(
_FALLBACK_HEADER = "[Compaction fallback — LLM summariser unavailable]"
+_FALLBACK_PRIOR_PREFIX = "Prior context: "
_FALLBACK_USER_PREFIX = "User requests: "
_FALLBACK_TOOL_PREFIX = "Tool calls: "
-def _parse_prior_fallback(summary: str) -> tuple[list[str], list[str]]:
- """Extract user_lines and tool_names from a previous fallback summary.
+def _parse_prior_fallback(summary: str) -> tuple[list[str], list[str], str | None]:
+ """Extract structured fields from a previous fallback summary.
+
+ Returns ``(user_lines, tool_names, prior_context)``. ``prior_context``
+ is the multi-line text that originally followed the ``Prior context:``
+ marker (a real LLM summary that the previous fallback wrapped). It is
+ forwarded so an outage spanning multiple compactions doesn't drop the
+ real summary that preceded it.
Format is the one this module emits:
[Compaction fallback — LLM summariser unavailable]
+ Prior context: <possibly multi-line real summary>
User requests: line1; line2
Tool calls: bash, read_file
- Returns ``([], [])`` if either marker is absent.
+ ``Prior context:`` may span multiple lines (the embedded real summary
+ has its own internal line breaks); we collect everything from that
+ marker until the next ``User requests:`` / ``Tool calls:`` line.
"""
user_lines: list[str] = []
tool_names: list[str] = []
+ prior_context_lines: list[str] = []
+ in_prior_context = False
+
for line in summary.splitlines():
if line.startswith(_FALLBACK_USER_PREFIX):
+ in_prior_context = False
user_lines = [
s.strip()
for s in line[len(_FALLBACK_USER_PREFIX) :].split(";")
if s.strip()
]
elif line.startswith(_FALLBACK_TOOL_PREFIX):
+ in_prior_context = False
tool_names = [
s.strip()
for s in line[len(_FALLBACK_TOOL_PREFIX) :].split(",")
if s.strip()
]
- return user_lines, tool_names
+ elif line.startswith(_FALLBACK_PRIOR_PREFIX):
+ in_prior_context = True
+ prior_context_lines.append(line[len(_FALLBACK_PRIOR_PREFIX) :])
+ elif in_prior_context:
+ prior_context_lines.append(line)
+
+ prior_context = (
+ "\n".join(prior_context_lines).rstrip() if prior_context_lines else None
+ )
+ return user_lines, tool_names, prior_context
def build_fallback_summary(
@@ -323,13 +347,21 @@ def build_fallback_summary(
if existing and existing.summary:
if existing.is_fallback:
# Merge the prior fallback's structured fields into the current
- # turn — never embed the prior summary text. Preserves order
- # (oldest user request first) and dedupes by exact match.
- prior_users, prior_tools = _parse_prior_fallback(existing.summary)
+ # turn — never embed the prior summary text whole (that grows
+ # unboundedly across an outage). User lines / tool names are
+ # deduped and re-rendered. If the prior fallback embedded a
+ # real LLM summary under ``Prior context:``, forward it so an
+ # outage spanning multiple compactions doesn't drop everything
+ # that was summarised before the LLM went down.
+ prior_users, prior_tools, prior_real = _parse_prior_fallback(
+ existing.summary
+ )
user_lines = list(dict.fromkeys(prior_users + user_lines))[:5]
tool_names = list(dict.fromkeys(prior_tools + tool_names))
+ if prior_real:
+ parts.append(f"{_FALLBACK_PRIOR_PREFIX}{prior_real}")
else:
- parts.append(f"Prior context: {existing.summary}")
+ parts.append(f"{_FALLBACK_PRIOR_PREFIX}{existing.summary}")
if user_lines:
parts.append(_FALLBACK_USER_PREFIX + "; ".join(user_lines))
if tool_names:
diff --git a/tests/middleware/compaction/test_summarizer.py b/tests/middleware/compaction/test_summarizer.py
index 9257e87..37bc171 100644
--- a/tests/middleware/compaction/test_summarizer.py
+++ b/tests/middleware/compaction/test_summarizer.py
@@ -555,3 +555,49 @@ def test_fallback_summary_after_real_summary_still_embeds_prior() -> None:
state = build_fallback_summary(msgs, existing=real_prior)
assert "Prior context:" in state.summary
assert "build the thing" in state.summary
+
+
+def test_fallback_preserves_real_prior_across_multiple_outage_turns() -> None:
+ """Codex P2: real summary → fallback → fallback. The 2nd fallback must
+ still carry the real summary's prior context, otherwise an outage of
+ more than one compaction cycle drops everything summarised before it."""
+ from cubepi.middleware.compaction.state import CompactionState
+ from cubepi.middleware.compaction.summarizer import build_fallback_summary
+
+ # Step 1: a real LLM summary covering "early work".
+ real_summary = CompactionState(
+ summary="## Goal\nbuild the thing\n## Decisions\nused approach X",
+ is_fallback=False,
+ )
+
+ # Step 2: LLM goes down → first fallback, which embeds the real summary.
+ msgs_fb1 = [
+ UserMessage(content=[TextContent(text="task during outage 1")]),
+ AssistantMessage(
+ content=[ToolCall(id="c1", name="bash", arguments={"q": "x"})]
+ ),
+ ]
+ fb1 = build_fallback_summary(msgs_fb1, existing=real_summary)
+ assert "build the thing" in fb1.summary # real summary embedded
+ assert "task during outage 1" in fb1.summary
+
+ # Step 3: LLM STILL down → second fallback chained to first fallback.
+ msgs_fb2 = [
+ UserMessage(content=[TextContent(text="task during outage 2")]),
+ AssistantMessage(
+ content=[ToolCall(id="c2", name="grep", arguments={"q": "y"})]
+ ),
+ ]
+ fb2 = build_fallback_summary(msgs_fb2, existing=fb1)
+
+ # Critical: the real prior context (## Goal / ## Decisions) must
+ # still be reachable in the 2nd fallback. Otherwise multi-turn
+ # outages erase everything pre-outage.
+ assert "build the thing" in fb2.summary
+ assert "used approach X" in fb2.summary
+ # User-line merging still works.
+ assert "task during outage 1" in fb2.summary
+ assert "task during outage 2" in fb2.summary
+ # Tool-name merging still works (dedup + ordering).
+ assert "bash" in fb2.summary
+ assert "grep" in fb2.summary