Skip to content

The agent that grows with you

feat(sessions): persist the consecutive-user merge witness on the survivor row

Evaf51d0a723384
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 4b6640384a2..562e031afd8 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -23,7 +23,7 @@ from agent.memory_manager import sanitize_context
from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
from agent.trajectory import save_trajectory as _save_trajectory_to_file
-from agent.message_metadata import DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS
from agent.transcript_repair import sync_flushed_message_markers
@@ -238,6 +238,10 @@ def _db_flush_row(agent, msg: Dict, is_current_turn_user: bool) -> Dict[str, Any
row["_row_id"] = msg["_row_id"]
if isinstance(msg.get(MESSAGE_UID), str) and msg[MESSAGE_UID]:
row[MESSAGE_UID] = msg[MESSAGE_UID]
+ if isinstance(msg.get(ABSORBED_MESSAGE_UIDS), list) and msg[ABSORBED_MESSAGE_UIDS]:
+ # The merge witness rides on the survivor's row (an owned column: a row-addressed rewrite of the
+ # survivor writes it too), so a restart sees which rows the composite folded.
+ row[ABSORBED_MESSAGE_UIDS] = list(msg[ABSORBED_MESSAGE_UIDS])
if isinstance(msg.get(DB_ROW_SNAPSHOT), str):
row[DB_ROW_SNAPSHOT] = msg[DB_ROW_SNAPSHOT]
return row
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
index e1b6ba04351..08c785035ed 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -9,7 +9,7 @@ import sqlite3
from typing import Any, Callable, Dict, List, Mapping
from agent.context_compressor import _DB_PERSISTED_MARKER
-from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID
from hermes_state_common import _id_chunks, _placeholders
from hermes_state_messages import _MESSAGE_WRITE_COLUMNS
@@ -278,6 +278,8 @@ def sync_flushed_message_markers(batch_msgs: List[Dict[str, Any]], batch_rows: L
written["_row_id"] = row["_row_id"]
if isinstance(row.get(MESSAGE_UID), str) and row[MESSAGE_UID]:
written[MESSAGE_UID] = row[MESSAGE_UID]
+ if isinstance(row.get(ABSORBED_MESSAGE_UIDS), list) and row[ABSORBED_MESSAGE_UIDS]:
+ written[ABSORBED_MESSAGE_UIDS] = list(row[ABSORBED_MESSAGE_UIDS])
if isinstance(row.get("timestamp"), (int, float)):
written["timestamp"] = row["timestamp"]
if isinstance(row.get(DB_ROW_SNAPSHOT), str):
diff --git a/hermes_state.py b/hermes_state.py
index ade971bfb22..83acb04bd83 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1610,7 +1610,8 @@ class SessionDB(
"id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, "
"finish_reason, reasoning, reasoning_content, reasoning_details, "
"codex_reasoning_items, codex_message_items, platform_message_id, observed, "
- "_compressed_summary, timestamp, active, api_content, display_kind, display_metadata, message_uid"
+ "_compressed_summary, timestamp, active, api_content, display_kind, display_metadata, message_uid, "
+ "absorbed_message_uids"
)
# ── Meta key/value (scheduler bookkeeping) ──
diff --git a/hermes_state_common.py b/hermes_state_common.py
index af26369e8d4..ab8363f3c00 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -452,7 +452,8 @@ CREATE TABLE IF NOT EXISTS messages (
display_metadata TEXT,
display_identity BLOB,
display_order INTEGER,
- message_uid TEXT
+ message_uid TEXT,
+ absorbed_message_uids TEXT
);
CREATE TABLE IF NOT EXISTS session_model_usage (
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index cd4af36dfc3..553d7e91b7c 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -15,7 +15,7 @@ from agent.context_compressor import (
_DB_PERSISTED_MARKER as _DB_PERSISTED_MARKER_KEY, MODEL_ONLY_DISPLAY_METADATA_KEY, _is_checkpoint_item,
_newest_checkpoint_carrier, split_user_originated_turn)
from agent.memory_manager import sanitize_context
-from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID
from agent.message_sanitization import _sanitize_surrogates
from hermes_cli.timefmt import coerce_epoch
from hermes_state_common import (
@@ -29,8 +29,8 @@ _INSERT_MESSAGE_SQL = """INSERT INTO messages (session_id, role, content, tool_c
tool_calls, tool_name, effect_disposition, timestamp, token_count, finish_reason,
reasoning, reasoning_content, reasoning_details, codex_reasoning_items,
codex_message_items, platform_message_id, observed, _compressed_summary, active, api_content, display_kind,
- display_metadata, display_identity, message_uid)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
+ display_metadata, display_identity, message_uid, absorbed_message_uids)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
# Every column this module knows how to read: the ones it writes plus the three SQLite/compaction
# owns. `_row_to_message_dict` drops raw bytes ONLY outside this set — a schema column keeps its
# key (and its typed decoder) even when a row holds a BLOB, so no reader ever loses msg["content"].
@@ -98,6 +98,23 @@ def _message_uid_or_none(msg: Dict[str, Any]) -> Optional[str]:
return uid if isinstance(uid, str) and uid else None
+def _uid_list(value: Any) -> List[str]:
+ """Normalize a uid list (a live list, or the JSON text an export/import carries) to unique non-empty
+ strings in order; anything else is ``[]``."""
+ if isinstance(value, str):
+ value = _json_or(value, [], "Failed to deserialize a message uid list, falling back to []")
+ if not isinstance(value, list):
+ return []
+ return list(dict.fromkeys(item for item in value if isinstance(item, str) and item))
+
+
+def _uid_list_json(msg: Dict[str, Any], live_key: str, column: str) -> Optional[str]:
+ """JSON text for a uid-list column, read from the live key first (flushed dicts, batch rows) and the
+ column name second (import payloads); ``None`` when empty."""
+ uids = _uid_list(msg.get(live_key) if live_key in msg else msg.get(column))
+ return json.dumps(uids) if uids else None
+
+
def _parse_tool_calls(tool_calls: Any) -> Any:
"""tool_calls is a list (live agent) or JSON string (import/export); parse so json.dumps never double-encodes."""
if not isinstance(tool_calls, str):
@@ -294,7 +311,7 @@ class SessionMessagesMixin:
1 if msg.get("observed") else 0, 1 if msg.get("_compressed_summary") else 0, 1,
_str_or_none(msg.get("api_content")), _str_or_none(msg.get("display_kind")),
display_metadata, self._display_identity(self._display_dedupe_key(identity_row)),
- _message_uid_or_none(msg))
+ _message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"))
@staticmethod
def _stamp_message_uid(msg: Dict[str, Any]) -> str:
@@ -345,6 +362,10 @@ class SessionMessagesMixin:
msg["observed"] = True
if row["_compressed_summary"]:
msg["_compressed_summary"] = True
+ if row[MESSAGE_UID]:
+ msg[MESSAGE_UID] = row[MESSAGE_UID]
+ if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):
+ msg[ABSORBED_MESSAGE_UIDS] = absorbed
if row["api_content"] is not None:
msg["api_content"] = row["api_content"]
if row["display_kind"] is not None:
@@ -1564,6 +1585,9 @@ class SessionMessagesMixin:
# projection (ACP, gateway, CLI, TUI, compression adoption), never opt-in like ``_row_id``.
if row[MESSAGE_UID]:
msg[MESSAGE_UID] = row[MESSAGE_UID]
+ # The persisted merge witness: which rows a consecutive-user merge folded into this one.
+ if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):
+ msg[ABSORBED_MESSAGE_UIDS] = absorbed
msg.update((col, row[col]) for col in ("api_content", "display_kind") if row[col])
if row["display_metadata"] and (decoded := self._decode_display_metadata(row["display_metadata"])) is not None:
msg["display_metadata"] = decoded
diff --git a/hermes_state_portability.py b/hermes_state_portability.py
index e51d1d1d5f1..c8608781719 100644
--- a/hermes_state_portability.py
+++ b/hermes_state_portability.py
@@ -30,7 +30,9 @@ _IMPORT_MESSAGE_TEXT_FIELDS = (
"tool_call_id", "tool_name", "effect_disposition", "finish_reason",
"reasoning", "reasoning_content", "platform_message_id", "message_id",
)
-_IMPORT_MESSAGE_JSON_FIELDS = ("reasoning_details", "codex_reasoning_items", "codex_message_items")
+_IMPORT_MESSAGE_JSON_FIELDS = (
+ "reasoning_details", "codex_reasoning_items", "codex_message_items", "absorbed_message_uids",
+)
_IMPORT_SESSION_INSERT_SQL = """INSERT INTO sessions (
id, source, user_id, model, model_config, system_prompt,
system_prompt_hash,
diff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.py
index c6fc1dd6b1e..1bec373ab71 100644
--- a/tests/agent/test_context_engine_message_uid.py
+++ b/tests/agent/test_context_engine_message_uid.py
@@ -186,6 +186,34 @@ def test_consecutive_user_merge_keeps_the_first_uid_and_records_the_absorbed_one
assert "_absorbed_row_ids" not in a
+def test_restart_after_a_merge_still_sees_the_composites_constituents(db):
+ """A dangling user row, a restart, the next prompt merged into it, a turn flush, another restart: the
+ restored survivor names the absorbed row by uid instead of leaving the engine to parse ``\\n\\n``."""
+ sid = "20260928_120300_witness"
+ db.create_session(sid, "cli", model="test/model")
+ db.append_message(session_id=sid, role="user", content="unanswered before the crash")
+ dangling_uid = db.get_messages_as_conversation(sid)[0]["message_uid"]
+ # Restart: the ACP/gateway restore shape, then the next prompt lands and the pre-request repair merges.
+ history = db.get_messages_as_conversation(sid, repair_alternation=True, include_row_ids=True)
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ prompt = {"role": "user", "content": "next prompt"}
+ messages = history + [prompt]
+ agent._persist_user_message_idx = 1
+ agent._persist_session(messages, conversation_history=history) # the turn-start flush of the prompt
+ from agent.agent_runtime_helpers import repair_message_sequence
+ repair_message_sequence(agent, messages)
+ assert len(messages) == 1 and messages[0]["message_uid"] == dangling_uid
+ assert messages[0]["_absorbed_message_uids"] == [prompt["message_uid"]]
+ messages.append({"role": "assistant", "content": "reply"})
+ agent._persist_session(messages, conversation_history=None)
+ # Second restart.
+ again = db.get_messages_as_conversation(sid, repair_alternation=True)
+ survivor = next(m for m in again if m["message_uid"] == dangling_uid)
+ assert survivor["content"].startswith("unanswered before the crash")
+ assert prompt["message_uid"] in survivor["_absorbed_message_uids"]
+
+
def test_the_uid_never_reaches_the_provider_copy():
from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.py
index 11b86f3964f..c8a53a4a85f 100644
--- a/tests/hermes_state/test_message_uid.py
+++ b/tests/hermes_state/test_message_uid.py
@@ -204,3 +204,58 @@ class TestCopyPathsKeepTheUid:
assert [r["message_uid"] for r in _rows(other, "s")] == [r["message_uid"] for r in stored]
finally:
other.close()
+
+
+def _absorbed(db, sid):
+ return [r[0] for r in db._conn.execute(
+ "SELECT absorbed_message_uids FROM messages WHERE session_id = ? AND active = 1 ORDER BY id", (sid,))]
+
+
+class TestPersistedMergeWitness:
+ """``_absorbed_message_uids`` (which rows a consecutive-user merge folded into the survivor) rides on the
+ survivor's row, so a consumer that restarts after the merge still knows the composite's constituents."""
+
+ def test_flushed_survivor_persists_the_absorbed_uids_and_restore_returns_them(self, db):
+ from agent.agent_runtime_helpers import _merge_consecutive_users
+
+ db.create_session("s", "cli")
+ dangling = {"role": "user", "content": "first, never answered"}
+ db.append_messages_batch("s", [dangling])
+ prompt = {"role": "user", "content": "second"}
+ db.append_messages_batch("s", [prompt])
+ _merge_consecutive_users([dangling, prompt])
+ assert dangling["_absorbed_message_uids"] == [prompt["message_uid"]]
+ # The survivor re-flushes as a row-addressed rewrite of its own row (same id, same uid).
+ db.append_messages_batch("s", [dangling])
+ rows = _rows(db, "s")
+ assert [r["content"] for r in rows] == ["first, never answered\n\nsecond", "second"]
+ assert rows[0]["message_uid"] == dangling["message_uid"]
+ assert _absorbed(db, "s") == ['["%s"]' % prompt["message_uid"], None]
+ restored = db.get_messages_as_conversation("s")
+ assert restored[0]["_absorbed_message_uids"] == [prompt["message_uid"]]
+ assert "_absorbed_message_uids" not in restored[1]
+
+ def test_a_survivor_inserted_as_a_fresh_row_carries_the_witness(self, db):
+ db.create_session("s", "cli")
+ composite = {"role": "user", "content": "a\n\nb", "message_uid": "a" * 32,
+ "_absorbed_message_uids": ["b" * 32, "c" * 32]}
+ db.append_messages_batch("s", [composite])
+ assert _absorbed(db, "s") == ['["%s", "%s"]' % ("b" * 32, "c" * 32)]
+ assert db.get_messages_as_conversation("s")[0]["_absorbed_message_uids"] == ["b" * 32, "c" * 32]
+
+ def test_compaction_copy_and_export_import_keep_the_witness(self, db, tmp_path):
+ db.create_session("s", "cli")
+ composite = {"role": "user", "content": "a\n\nb", "message_uid": "a" * 32,
+ "_absorbed_message_uids": ["b" * 32]}
+ db.append_messages_batch("s", [composite, {"role": "assistant", "content": "ok"}])
+ restored = db.get_messages_as_conversation("s")
+ db.archive_and_compact("s", [{"role": "user", "content": "[CONTEXT COMPACTION] s"},
+ copy.copy(restored[0]), copy.copy(restored[1])])
+ assert _absorbed(db, "s") == [None, '["%s"]' % ("b" * 32), None]
+ payload = db.export_session("s")
+ other = SessionDB(db_path=tmp_path / "other.db")
+ try:
+ assert other.import_sessions([payload])["ok"]
+ assert other.get_messages_as_conversation("s")[1]["_absorbed_message_uids"] == ["b" * 32]
+ finally:
+ other.close()
diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.md
index 3135e59aea2..52a2c31e063 100644
--- a/website/docs/developer-guide/context-engine-plugin.md
+++ b/website/docs/developer-guide/context-engine-plugin.md
@@ -160,11 +160,13 @@ What the host guarantees:
sanitizer's row-addressed rewrite, the interrupted-stream fill. Treat
`(message_uid, content)` as a *version* of the message; never fail closed on
a content change under a known uid.
-- **Merges keep the first constituent's uid.** When alternation repair merges
- consecutive user turns, the survivor keeps its own uid and records the
- absorbed rows' uids in `_absorbed_message_uids` (live-only, in absorption
- order), so an engine can see that `A\n\nB` is the host's fold of `A` and `B`
- rather than a new message.
+- **Merges keep the first constituent's uid and record the rest.** When
+ alternation repair merges consecutive user turns, the survivor keeps its own
+ uid and records the absorbed rows' uids in `_absorbed_message_uids` (in
+ absorption order). The list is persisted on the survivor's row
+ (`messages.absorbed_message_uids`) and restored with it, so after a restart an
+ engine still sees that `A\n\nB` is the host's fold of `A` and `B` rather
+ than a new message.
- **Engine-authored rows keep the uid the engine sets.** If your `compress()`
output pre-stamps `message_uid` on a summary carrier, the host writes that
value; rows without one are minted at insert.
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 5303ff43ff3..992ba5d4de9 100644
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@ -207,7 +207,7 @@ later.
Abridged — the full schema also includes `effect_disposition`,
`platform_message_id`, `observed`, `active`, `compacted`, `api_content`,
-`display_kind`, `display_metadata`, and `message_uid`:
+`display_kind`, `display_metadata`, `message_uid`, and `absorbed_message_uids`:
```sql
CREATE TABLE IF NOT EXISTS messages (
@@ -243,6 +243,7 @@ Notes:
- `api_content` is a byte-fidelity sidecar: the exact content string sent to the API for this message when it differs from `content` (ephemeral memory/plugin injections, persist overrides). It preserves the wire bytes for prompt-cache-stable replay — stored as sent, except lone surrogates, which sqlite3 cannot bind and which the conversation loop scrubs from every outgoing payload anyway. `NULL` means `content` was sent verbatim.
- Timestamps are Unix epoch floats (`time.time()`)
- `message_uid` is the durable per-message id (32 hex, `uuid4().hex`): minted once at a row's first insert and copied by every clone (in-place compaction generations, rotation children, concurrent-tail clones, `replace_messages` re-issues, export/import), so one logical message keeps one uid while its physical `id` changes. Row-addressed rewrites leave it alone. It is restored on every projection (`get_messages_as_conversation` sets it unconditionally; `_row_id` stays opt-in) and stripped from provider requests. Context engines key their own per-message state on it — see [Context Engine Plugins](./context-engine-plugin.md#stable-message-identity-message_uid).
+- `absorbed_message_uids` is the merge witness: a JSON list of the `message_uid`s that alternation repair folded into this user row (the survivor keeps its own uid). Written when the survivor is flushed, rewritten with it, restored as the live `_absorbed_message_uids`, `NULL` on rows that absorbed nothing.
### FTS5 Full-Text Search