Skip to content

The agent that grows with you

fix(gateway): replay the compactor's restated in-flight task unstamped too

Teknium899b7df62175
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 0b08f41cdec..d8d01fa9dcd 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -4907,8 +4907,7 @@ Write only the summary body. Do not include any preamble or prefix."""
last_visible_role = _last_template_visible_role(compressed)
if self._has_merged_inflight_replay(inflight):
- # Never copy a summary carrier (metadata would mark the replay
- # synthetic): restate as a plain user row.
+ # Never copy a summary carrier (its metadata marks it synthetic): restate as a plain user row.
replay = {"role": "user", "content": task_text}
else:
replay = _fresh_compaction_message_copy(inflight)
@@ -4935,7 +4934,8 @@ Write only the summary body. Do not include any preamble or prefix."""
# occurrence of it. When the original survived in the protected head,
# retaining it gives the durable transcript two active rows with the
# same message_uid and renders the request twice after reload.
- from agent.message_metadata import MESSAGE_UID, message_uid_or_none, record_absorbed_message
+ from agent.message_metadata import MESSAGE_UID, mark_inflight_restatement, message_uid_or_none, record_absorbed_message
+ mark_inflight_restatement(replay) # only the standalone row: the merged layout is already a summary
if replay_uid := message_uid_or_none(replay):
before = len(compressed)
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index 5a1669d594f..a7c8d4d0f03 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -93,6 +93,29 @@ def stamp_message_uid(msg: MutableMapping[str, Any]) -> str:
return uid
+# Producer-owned provenance for the compressor's standalone in-flight-task restatement. It rides in
+# display_metadata (persisted by SessionDB, popped from every wire copy) so gateway replay can send the
+# row unstamped, as the compaction turn did; a human pasting the header text carries no flag.
+INFLIGHT_TASK_RESTATEMENT = "compaction_inflight_task_restatement"
+
+
+def mark_inflight_restatement(msg: MutableMapping[str, Any]) -> None:
+ metadata = msg.get("display_metadata")
+ 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."""
+ 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 {}
+
+
+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))
+
+
_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 f64f7d1fd9c..13beb29570b 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
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_identity_fields, is_compaction_scaffolding, restatement_metadata
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,9 +1152,9 @@ def _build_replay_entry(
entry[_rkey] = _rval
if preserve_timestamp and msg.get("timestamp"):
entry["timestamp"] = msg["timestamp"]
- # Replay rebuilds the SAME conversation for its next turn: every role keeps its uid and merge witness, so a
- # context engine sees the uids the store holds. Tool-call uid maps stay with the rows that still carry
- # their calls (those pass through whole); on a plain row a leftover map would name calls it no longer has.
+ entry.update(restatement_metadata(msg)) # a proactive prune re-persists this view: keep the flag
+ # 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)
# Replay rewrites are view-only: keep the durable-row stamp so marker-only
# flushes skip rows already in state.db (#121462/#123462).
@@ -1302,8 +1302,7 @@ def _build_gateway_agent_history(
continue
# Keep user timestamps for the stale-dangerous-confirmation stripper in agent/replay_cleanup.py.
entry = _build_replay_entry(role, content, msg, preserve_timestamp=(role == "user"))
- # Compaction sent summaries unstamped; stamping them on replay breaks the cached prefix.
- if inject_timestamps and role == "user" and isinstance(content, str) and not msg.get("_compressed_summary"):
+ if inject_timestamps and role == "user" and isinstance(content, str) and not is_compaction_scaffolding(msg):
rendered = _render_msg_ts(content, replay_timestamp, tz=_msg_tz)
# Preserve only a sidecar matching the complete rendered message,
# optionally followed by the normal context separator. Cleanup
diff --git a/tests/gateway/test_message_timestamps.py b/tests/gateway/test_message_timestamps.py
index fce97a71a29..d8ab36978e8 100644
--- a/tests/gateway/test_message_timestamps.py
+++ b/tests/gateway/test_message_timestamps.py
@@ -224,3 +224,57 @@ def test_regular_user_message_still_replays_with_timestamp():
history, _ = _build_gateway_agent_history([message], inject_timestamps=True)
assert history[0]["content"].endswith(message["content"])
assert history[0]["content"] != message["content"]
+
+
+def test_compactor_restatement_replays_unstamped_through_session_db(tmp_path):
+ """Compaction sends its restated in-flight task unstamped; a reload must replay those exact bytes."""
+ from types import SimpleNamespace
+ from unittest.mock import patch
+
+ from agent.context_compressor import ContextCompressor, _INFLIGHT_TASK_REPLAY_HEADER
+ from gateway.config import GatewayConfig
+ from gateway.run import _build_gateway_agent_history
+ from gateway.session import SessionStore
+ from hermes_state import SessionDB
+ from hermes_time import get_timezone
+
+ sent_at = _epoch(2026, 4, 28, 13, 40, 53)
+ messages = [{"role": "system", "content": "sys"},
+ {"role": "user", "content": "Summarize project files", "timestamp": sent_at}]
+ for i in range(40):
+ messages += [
+ {"role": "assistant", "content": f"step {i}", "tool_calls": [
+ {"id": f"c{i}", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": f"c{i}", "content": "fixture " * 200},
+ ]
+ compressor = ContextCompressor(model="m", quiet_mode=True, config_context_length=100_000,
+ protect_first_n=2, protect_last_n=2)
+ compressor.tail_token_budget = 500
+ summary = SimpleNamespace(choices=[SimpleNamespace(
+ message=SimpleNamespace(content="## Historical Task Snapshot\nx\n## Summary\ny"), finish_reason="stop")])
+ with patch("agent.context_compressor.call_llm", return_value=summary):
+ sent = [m for m in compressor.compress(messages, current_tokens=200_000, force=True) if m["role"] != "system"]
+ sent.append({"role": "assistant", "content": "Done"})
+ # A human pasting the header text is still a message someone sent: it keeps its stamp.
+ pasted = f"{_INFLIGHT_TASK_REPLAY_HEADER}\nthis is a pasted log"
+ sent += [{"role": "user", "content": pasted, "timestamp": sent_at}, {"role": "assistant", "content": "ok"}]
+
+ 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", sent)
+ replay, _ = _build_gateway_agent_history(store.load_transcript("room"), inject_timestamps=True)
+ finally:
+ db.close()
+ store.close_all_db_handles()
+
+ def restatement(rows):
+ return next((m["content"] for m in rows if m["role"] == "user"
+ and str(m["content"]).startswith(_INFLIGHT_TASK_REPLAY_HEADER)), None)
+
+ assert restatement(sent) is not None
+ 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())