Skip to content

The agent that grows with you

fix(gateway): keep the compaction summary flag on replayed rows so a proactive prune re-persists it

Teknium58dd5b9dc7df
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index a7c8d4d0f03..14e0bd82a6d 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -104,16 +104,19 @@ def mark_inflight_restatement(msg: MutableMapping[str, Any]) -> None:
msg["display_metadata"] = {**(metadata if isinstance(metadata, dict) else {}), INFLIGHT_TASK_RESTATEMENT: True}
-def restatement_metadata(msg: Mapping[str, Any]) -> dict:
- """``{"display_metadata": {flag}}`` for a flagged row, else ``{}``: replay keeps only the flag."""
+def scaffolding_replay_fields(msg: Mapping[str, Any]) -> dict:
+ """The compaction-provenance fields replay keeps (summary flag, restatement flag), else ``{}``. A proactive
+ prune re-persists the replayed view, so a dropped flag would get the row stamped on the next replay."""
metadata = msg.get("display_metadata")
- flagged = isinstance(metadata, dict) and bool(metadata.get(INFLIGHT_TASK_RESTATEMENT))
- return {"display_metadata": {INFLIGHT_TASK_RESTATEMENT: True}} if flagged else {}
+ fields: dict = {"_compressed_summary": True} if msg.get("_compressed_summary") else {}
+ if isinstance(metadata, dict) and metadata.get(INFLIGHT_TASK_RESTATEMENT):
+ fields["display_metadata"] = {INFLIGHT_TASK_RESTATEMENT: True}
+ return fields
def is_compaction_scaffolding(msg: Mapping[str, Any]) -> bool:
"""Compaction sent its summary and restatement rows unstamped; a replay stamp would break the cached prefix."""
- return bool(msg.get("_compressed_summary")) or bool(restatement_metadata(msg))
+ return bool(scaffolding_replay_fields(msg))
_IDENTITY_FIELD_TYPES = ((MESSAGE_UID, str), (ABSORBED_MESSAGE_UIDS, list), (TOOL_CALL_UIDS, dict), (TOOL_CALL_UID, str))
diff --git a/gateway/run.py b/gateway/run.py
index 13beb29570b..acda4ddea70 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -40,7 +40,7 @@ from agent.conversation_compression import (
from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, RETIRED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS
from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX
from agent.interrupt_compat import request_hard_interrupt
-from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_identity_fields, is_compaction_scaffolding, restatement_metadata
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_identity_fields, is_compaction_scaffolding, scaffolding_replay_fields
from agent.turn_context import compression_made_progress
from agent.session_activity import ActivityProvenance, AwakeIdleMeter
from hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get
@@ -1152,7 +1152,7 @@ def _build_replay_entry(
entry[_rkey] = _rval
if preserve_timestamp and msg.get("timestamp"):
entry["timestamp"] = msg["timestamp"]
- entry.update(restatement_metadata(msg)) # a proactive prune re-persists this view: keep the flag
+ entry.update(scaffolding_replay_fields(msg)) # a proactive prune re-persists this view: keep the flags
# Replay rebuilds the SAME conversation: every role keeps its uid and merge witness, so a context engine sees the
# uids the store holds. Tool-call uid maps stay on rows that still carry their calls (those pass through whole).
copy_identity_fields({key: msg[key] for key in (MESSAGE_UID, ABSORBED_MESSAGE_UIDS) if key in msg}, entry)
diff --git a/tests/gateway/test_message_timestamps.py b/tests/gateway/test_message_timestamps.py
index 5a8556c7b32..217cfe9fc25 100644
--- a/tests/gateway/test_message_timestamps.py
+++ b/tests/gateway/test_message_timestamps.py
@@ -283,3 +283,38 @@ def test_compactor_restatement_replays_unstamped_through_session_db(tmp_path):
assert restatement(replay) == restatement(sent)
assert next(m for m in replay if m["role"] == "user" and str(m["content"]).endswith("this is a pasted log"))[
"content"] == render_user_content_with_timestamp(pasted, sent_at, tz=get_timezone())
+
+
+def test_compaction_summary_stays_unstamped_across_real_prune(tmp_path):
+ """A proactive prune re-persists the replayed view; the summary carrier must keep its flag through it."""
+ from agent.context_compressor import ContextCompressor
+ from gateway.config import GatewayConfig
+ from gateway.run import _build_gateway_agent_history
+ from gateway.session import SessionStore
+ from hermes_state import SessionDB
+
+ summary = {"role": "user", "content": "[CONTEXT COMPACTION — REFERENCE ONLY] retained summary",
+ "_compressed_summary": True}
+ rows = [summary, {"role": "assistant", "content": "Continue"}]
+ for i in range(5):
+ rows += [{"role": "assistant", "content": None, "tool_calls": [
+ {"id": f"c{i}", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": f"c{i}", "content": f"file {i} " + f"unique output {i} " * 5000}]
+ rows += [{"role": "user", "content": "new task"}, {"role": "assistant", "content": "working"}]
+ db = SessionDB(db_path=tmp_path / "state.db")
+ store = SessionStore(tmp_path / "sessions", GatewayConfig())
+ store._db = db
+ try:
+ db.create_session("room", source="matrix")
+ db.archive_and_compact("room", rows)
+ first, _ = _build_gateway_agent_history(store.load_transcript("room"), inject_timestamps=True)
+ compressor = ContextCompressor(model="m", quiet_mode=True, config_context_length=100_000, protect_first_n=1,
+ protect_last_n=2, proactive_prune_tokens=1, proactive_prune_min_reclaim_tokens=1)
+ compressor._session_db, compressor._session_id = db, "room"
+ _, pruned = compressor.prune_tool_results_only(first, current_tokens=100_000)
+ replay, _ = _build_gateway_agent_history(store.load_transcript("room"), inject_timestamps=True)
+ finally:
+ db.close()
+ store.close_all_db_handles()
+ assert pruned
+ assert first[0]["content"] == replay[0]["content"] == summary["content"]