Skip to content

The agent that grows with you

feat(sessions): give every persisted message a durable message_uid that reaches context engines

Eva751d8526e350
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index dda9f03686a..0fcd6e46758 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -19,6 +19,7 @@ from hermes_cli.timeouts import get_provider_request_timeout
from agent.message_sanitization import (
_FULL_ARGS_LOG_BOUND, coalesce_tool_call_id, coerce_tool_name, tool_call_id_variants, tool_result_id_variants
)
+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID
from agent.prompt_builder import STEER_DISPLAY_KIND, steer_user_row
from agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_message
from agent.think_scrubber import THINK_TAG_NAMES
@@ -452,8 +453,11 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any]) -> None:
"""Record durable ids a merge folded into *survivor* and then dropped from the list.
- No-op when the dropped dict names no row. An empty incoming turn still merges,
- and stamping an empty list would change a message that absorbed nothing.
+ Both the physical ``_row_id`` (``_absorbed_row_ids``, consumed by the in-place archive) and the durable
+ ``message_uid`` (``_absorbed_message_uids``, the merge witness context engines read) are recorded; the
+ survivor keeps its own uid, so a composite is "first constituent + absorbed". No-op when the dropped
+ dict names no row and no uid. An empty incoming turn still merges, and stamping an empty list would
+ change a message that absorbed nothing.
"""
ids = []
row_id = dropped.get("_row_id")
@@ -462,12 +466,23 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any]) ->
for older in dropped.get("_absorbed_row_ids") or ():
if isinstance(older, int) and not isinstance(older, bool) and older > 0 and older not in ids:
ids.append(older)
- if not ids:
- return
- absorbed = survivor.setdefault("_absorbed_row_ids", [])
- for row_id in ids:
- if row_id not in absorbed:
- absorbed.append(row_id)
+ if ids:
+ absorbed = survivor.setdefault("_absorbed_row_ids", [])
+ for row_id in ids:
+ if row_id not in absorbed:
+ absorbed.append(row_id)
+ uids = []
+ uid = dropped.get(MESSAGE_UID)
+ if isinstance(uid, str) and uid:
+ uids.append(uid)
+ for older in dropped.get(ABSORBED_MESSAGE_UIDS) or ():
+ if isinstance(older, str) and older and older not in uids:
+ uids.append(older)
+ if uids:
+ absorbed_uids = survivor.setdefault(ABSORBED_MESSAGE_UIDS, [])
+ for uid in uids:
+ if uid not in absorbed_uids:
+ absorbed_uids.append(uid)
def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index a4ee2b8b233..68e31400262 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -20,8 +20,16 @@ REPAIR_BOOKKEEPING_FIELDS = frozenset({DB_ROW_SNAPSHOT, CANONICAL_ROW})
# (agent_runtime_helpers._merge_consecutive_users); the persist override keeps it.
# It repeats the row's own content, so pricing it would double the estimate.
MERGED_TURN_PREFIX = "_merged_turn_prefix"
+# The durable per-message id (``messages.message_uid``): minted once at the row's first insert and kept by
+# every host copy of that logical message (in-place compaction generation, rotation child, concurrent-tail
+# clone, replace re-issue, rewrite in place). Unlike ``_row_id`` (a physical id re-issued per copy, opt-in on
+# restore) it is restored unconditionally, so context engines can key on it across restarts and boundaries.
+MESSAGE_UID = "message_uid"
+# Live-only bookkeeping on a consecutive-user merge survivor: the ``message_uid`` of each absorbed row, in
+# absorption order (the uid sibling of ``_absorbed_row_ids``). The survivor keeps the FIRST constituent's uid.
+ABSORBED_MESSAGE_UIDS = "_absorbed_message_uids"
PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(
- {"timestamp", "display_kind", "display_metadata", "_row_id", MERGED_TURN_PREFIX}
+ {"timestamp", "display_kind", "display_metadata", "_row_id", MERGED_TURN_PREFIX, MESSAGE_UID, ABSORBED_MESSAGE_UIDS}
) | REPAIR_BOOKKEEPING_FIELDS
_Message = TypeVar("_Message", bound=MutableMapping[str, Any])
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 680eedf76b5..4b6640384a2 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, REPAIR_BOOKKEEPING_FIELDS
+from agent.message_metadata import DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS
from agent.transcript_repair import sync_flushed_message_markers
@@ -236,6 +236,8 @@ def _db_flush_row(agent, msg: Dict, is_current_turn_user: bool) -> Dict[str, Any
}
if isinstance(msg.get("_row_id"), int):
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(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 a5d3988468d..e1b6ba04351 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -9,14 +9,15 @@ 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
+from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID
from hermes_state_common import _id_chunks, _placeholders
from hermes_state_messages import _MESSAGE_WRITE_COLUMNS
# Durable payload columns a row-addressed rewrite may change: every INSERT column except row identity,
-# role, active flag and the ones owned by the display index / timestamp / session linkage.
-_NON_PAYLOAD_COLUMNS = frozenset({"session_id", "role", "timestamp", "active", "display_identity"})
+# role, active flag and the ones owned by the display index / timestamp / session linkage. ``message_uid``
+# is identity too: a rewrite changes the message's content, never which logical message the row is.
+_NON_PAYLOAD_COLUMNS = frozenset({"session_id", "role", "timestamp", "active", "display_identity", MESSAGE_UID})
_REPAIR_COLUMNS = tuple(c for c in _MESSAGE_WRITE_COLUMNS if c not in _NON_PAYLOAD_COLUMNS)
# Columns same-process writers update after our flush (reactions / display-kind stamps, api_content
# backfill, codex reasoning backfill + checkpoint pruning, platform message ids). They are not part of the
@@ -150,6 +151,10 @@ def resolve_and_repair_transcript_batch(
"SELECT * FROM messages WHERE id = ? AND session_id = ?", (target_id, session_id)
).fetchone() if wrote else target_row
msg["timestamp"] = final_row["timestamp"]
+ # A row-addressed rewrite keeps the row's identity: the stored uid wins over whatever the live dict
+ # carried (a restored dict without one, or a dict stamped before a rolled-back insert).
+ if final_row[MESSAGE_UID]:
+ msg[MESSAGE_UID] = final_row[MESSAGE_UID]
msg[DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)
if adopt:
canonical = decode_row_fn(final_row)
@@ -271,6 +276,8 @@ def sync_flushed_message_markers(batch_msgs: List[Dict[str, Any]], batch_rows: L
written[_DB_PERSISTED_MARKER] = True
if isinstance(row.get("_row_id"), int):
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("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 11167754e52..ade971bfb22 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1610,7 +1610,7 @@ 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"
+ "_compressed_summary, timestamp, active, api_content, display_kind, display_metadata, message_uid"
)
# ── Meta key/value (scheduler bookkeeping) ──
diff --git a/hermes_state_common.py b/hermes_state_common.py
index e35e61a06a3..af26369e8d4 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -260,7 +260,7 @@ def _sql_session_last_active_by_id(session_id_expr: str) -> str:
f"(SELECT started_at FROM sessions _act_s WHERE _act_s.id = {session_id_expr})")
-SCHEMA_VERSION = 30
+SCHEMA_VERSION = 31
# Auto-maintenance VACUUMs only above this freelist fraction; below it a rewrite costs more I/O than it returns.
# Auto-maintenance only VACUUMs when at least this fraction of the database file is reclaimable (``PRAGMA
@@ -451,7 +451,8 @@ CREATE TABLE IF NOT EXISTS messages (
display_kind TEXT,
display_metadata TEXT,
display_identity BLOB,
- display_order INTEGER
+ display_order INTEGER,
+ message_uid TEXT
);
CREATE TABLE IF NOT EXISTS session_model_usage (
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 82e0187a5e7..cd4af36dfc3 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -8,13 +8,14 @@ import json
import logging
import re
import time
+import uuid
from typing import Any, Dict, List, Optional, Tuple
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
+from agent.message_metadata import 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 (
@@ -28,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)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
+ display_metadata, display_identity, message_uid)
+ 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"].
@@ -57,7 +58,7 @@ _DISPLAY_META_ROW_SQL = "SELECT display_metadata FROM messages WHERE id = ? AND
_DISPLAY_INDEX_MISSING_SQL = ("SELECT 1 FROM messages WHERE session_id = ?" + _DISPLAY_ACTIVE_CLAUSE
+ " AND (display_order IS NULL OR display_identity IS NULL) LIMIT 1")
_ACTIVE_IDS_SQL = "SELECT id FROM messages WHERE session_id = ? AND active = 1 ORDER BY id"
-_LIVE_IDENTITY_SQL = ("SELECT id, role, content, tool_call_id, tool_calls FROM messages "
+_LIVE_IDENTITY_SQL = ("SELECT id, role, content, tool_call_id, tool_calls, message_uid FROM messages "
"WHERE session_id = ? AND active = 1 ORDER BY id LIMIT ?")
_SET_COUNTERS_SQL = "UPDATE sessions SET message_count = ?, tool_call_count = ?"
_RESET_COUNTERS_SQL = "UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?"
@@ -90,6 +91,13 @@ def _coerce_timestamp(value: Any, default: float) -> float:
return 0.0 if result == 0.0 else result
+def _message_uid_or_none(msg: Dict[str, Any]) -> Optional[str]:
+ """The dict's ``message_uid`` when it is a non-empty string, else ``None`` (never coerced: an int or a
+ blank would be a bug upstream of the write, not an identity)."""
+ uid = msg.get(MESSAGE_UID)
+ return uid if isinstance(uid, str) and uid 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):
@@ -285,7 +293,22 @@ class SessionMessagesMixin:
msg.get("platform_message_id") or msg.get("message_id"),
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)))
+ display_metadata, self._display_identity(self._display_dedupe_key(identity_row)),
+ _message_uid_or_none(msg))
+
+ @staticmethod
+ def _stamp_message_uid(msg: Dict[str, Any]) -> str:
+ """The dict's ``message_uid``, minting one (``uuid4().hex``) when it carries none.
+
+ Minted ONCE per logical message, at its first insert, and stamped on the caller's dict so every
+ later insert of that dict (compaction generation, rotation handoff, replace) writes the same uid.
+ Never derived from content, timestamp or tool-call ids: two distinct messages may share all three.
+ """
+ uid = _message_uid_or_none(msg)
+ if uid is None:
+ uid = uuid.uuid4().hex
+ msg[MESSAGE_UID] = uid
+ return uid
def _serialized_message_row(
self, session_id: str, msg: Dict[str, Any], message_timestamp: float
@@ -371,6 +394,7 @@ class SessionMessagesMixin:
msg["display_metadata"] = self._encode_display_metadata(display_metadata)
tool_calls = _parse_tool_calls(tool_calls)
message_timestamp = _coerce_timestamp(timestamp, time.time())
+ self._stamp_message_uid(msg) # a fresh occurrence: mint its durable id
params = self._message_row_params(
session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=True)
def _do(conn):
@@ -395,6 +419,7 @@ class SessionMessagesMixin:
msg = {"content": content,
"display_kind": "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete",
"display_metadata": metadata}
+ self._stamp_message_uid(msg) # a fresh occurrence: mint its durable id
params = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)
def _do(conn):
@@ -690,6 +715,10 @@ class SessionMessagesMixin:
role = msg.get("role", "unknown")
tool_calls = _parse_tool_calls(msg.get("tool_calls"))
message_timestamp = _coerce_timestamp(msg.get("timestamp"), now_ts)
+ # The durable per-message id: kept when the dict carries one (a copy of an already-stored
+ # message), minted and stamped on the dict otherwise. Stamped BEFORE the bind so the row and
+ # the live dict never disagree.
+ self._stamp_message_uid(msg)
cur = conn.execute(_INSERT_MESSAGE_SQL, self._message_row_params(
session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=role == "assistant"))
# Keep the caller's live row aligned with the durable identity. Rows created without an explicit
@@ -788,7 +817,7 @@ class SessionMessagesMixin:
def _stamp_kept_live_prefix(self, live: list, messages: List[Dict[str, Any]]) -> int:
"""Length of the in-order prefix of *messages* already present as the leading live rows; each
- matched message gets its existing ``_row_id`` stamped, as a fresh insert would set it."""
+ matched message gets its existing ``_row_id`` (and ``message_uid``) stamped, as a fresh insert would set them."""
kept = 0
for row, msg in zip(live, messages):
role = msg.get("role", "unknown")
@@ -800,6 +829,8 @@ class SessionMessagesMixin:
if identity != self._row_identity(row[1], self._decode_content(row[2]), row[3], _parse_tool_calls(row[4])):
break
msg["_row_id"] = row[0]
+ if row[5]:
+ msg[MESSAGE_UID] = row[5]
kept += 1
return kept
@@ -1529,6 +1560,10 @@ class SessionMessagesMixin:
# the ENTIRE transcript on flush.
if include_row_ids and row["id"] is not None:
msg["_row_id"] = row["id"]
+ # The durable per-message id is part of the message, like ``timestamp``: restored on EVERY
+ # projection (ACP, gateway, CLI, TUI, compression adoption), never opt-in like ``_row_id``.
+ if row[MESSAGE_UID]:
+ msg[MESSAGE_UID] = row[MESSAGE_UID]
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_schema.py b/hermes_state_schema.py
index ffd06529fbb..9b1820b11b3 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -1051,6 +1051,14 @@ class SessionSchemaMixin:
if current_version < 25:
# v25: de-duplicate system prompt snapshots (old column stays a read fallback).
self._dedupe_legacy_system_prompts(cursor)
+ if current_version < 31:
+ # v31: ``messages.message_uid`` — the durable per-message id. New rows are minted at insert
+ # (``_insert_message_rows``); rows written before the column existed get theirs here, once, so
+ # every row a v31 store hands to a consumer carries one. Non-deterministic per row: two rows
+ # never share a backfilled uid.
+ cursor.execute(
+ "UPDATE messages SET message_uid = lower(hex(randomblob(16))) WHERE message_uid IS NULL"
+ )
fts_migrations_complete = True
if current_version < 30 and fts5_available:
# v29: cron sessions leave the trigram substring index (they stay in the word index);
diff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.py
new file mode 100644
index 00000000000..c6fc1dd6b1e
--- /dev/null
+++ b/tests/agent/test_context_engine_message_uid.py
@@ -0,0 +1,192 @@
+"""A context engine sees ``message_uid`` on every message the host hands it.
+
+The engine-facing surfaces are ``compress()`` (the live list), ``post_llm_call``'s
+``conversation_history`` (the same live dicts after the turn flush) and ``on_turn_complete``
+(structural clones). The id must reach all three after a cold restore that never asked for
+``_row_id``, survive the persist override and an in-place compaction commit, and never reach the
+provider. A consecutive-user merge keeps the first constituent's uid and records the absorbed ones.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from contextlib import closing
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from agent.context_engine import ContextEngine
+from hermes_state import SessionDB
+
+UID_LEN = 32
+
+
+class _CapturingEngine(ContextEngine):
+ """Records what compress() and on_turn_complete() receive; compress() returns marker-swept copies."""
+
+ last_prompt_tokens = 0
+
+ def __init__(self) -> None:
+ self.compress_input = None
+ self.turn_complete_messages = None
+ self._last_compress_aborted = False
+ self._last_summary_error = None
+ self.compression_count = 1
+
+ @property
+ def name(self) -> str:
+ return "capturing"
+
+ def update_from_response(self, usage):
+ pass
+
+ def should_compress(self, prompt_tokens=None):
+ return False
+
+ def compress(self, messages, current_tokens=None, focus_topic=None, force=False):
+ self.compress_input = [dict(m) for m in messages]
+ summary = {"role": "user", "content": "[CONTEXT COMPACTION] summary of prior turns"}
+ return [summary] + [dict(m) for m in messages[-2:]]
+
+ def on_turn_complete(self, messages, usage=None, **kwargs):
+ self.turn_complete_messages = messages
+
+ def _record_compression_failure_cooldown(self, *a, **k):
+ pass
+
+
+def _make_agent(session_db, session_id):
+ with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ api_key="test-key", base_url="https://openrouter.ai/api/v1", model="test/model", quiet_mode=True,
+ session_db=session_db, session_id=session_id, skip_context_files=True, skip_memory=True,
+ )
+ agent.compression_in_place = True
+ agent.context_compressor = _CapturingEngine()
+ return agent
+
+
+def _seed(db, sid, n=6):
+ db.create_session(sid, "cli", model="test/model")
+ for i in range(n):
+ db.append_message(session_id=sid, role="user" if i % 2 == 0 else "assistant", content=f"seed msg {i}")
+ return [dict(r) for r in db._conn.execute(
+ "SELECT id, content, message_uid FROM messages WHERE session_id = ? AND active = 1 ORDER BY id",
+ (sid,)).fetchall()]
+
+
+def db(tmp_path):
+ with closing(SessionDB(db_path=Path(tmp_path) / "state.db")) as handle:
+ yield handle
+
+
+def test_compress_input_after_a_cold_restore_carries_every_rows_uid(db):
+ """The ACP/gateway restore shape (no ``include_row_ids``) → compress() input → committed generation."""
+ from agent.conversation_compression import compress_context
+
+ sid = "20260928_120000_uid"
+ stored = _seed(db, sid)
+ restored = db.get_messages_as_conversation(sid, repair_alternation=True)
+ assert all("_row_id" not in m for m in restored)
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ agent._last_flushed_db_idx = len(restored)
+
+ compressed, _sp = compress_context(agent, restored, approx_tokens=100_000, system_message="sys")
+
+ engine = agent.context_compressor
+ assert [m.get("message_uid") for m in engine.compress_input] == [r["message_uid"] for r in stored]
+ # The committed generation: the copied tail keeps its uids, the summary got a fresh one.
+ active = [dict(r) for r in db._conn.execute(
+ "SELECT content, message_uid FROM messages WHERE session_id = ? AND active = 1 ORDER BY id", (sid,))]
+ assert [r["content"] for r in active] == [
+ "[CONTEXT COMPACTION] summary of prior turns", "seed msg 4", "seed msg 5"]
+ assert [r["message_uid"] for r in active[1:]] == [stored[4]["message_uid"], stored[5]["message_uid"]]
+ assert len(active[0]["message_uid"]) == UID_LEN
+ # And the live list the caller keeps carries the same uids (what the next compress()/post_llm_call sees).
+ assert [m.get("message_uid") for m in compressed] == [r["message_uid"] for r in active]
+
+
+def test_turn_flush_stamps_uids_on_the_live_dicts_post_llm_call_hands_over(db):
+ """``post_llm_call(conversation_history=list(messages))`` passes the live dicts; after the turn flush
+ every one of them carries the durable uid, including the current-turn user row."""
+ sid = "20260928_120100_flush"
+ db.create_session(sid, "cli", model="test/model")
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ messages = [{"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi"}]
+ agent._persist_user_message_idx = 0
+
+ agent._persist_session(messages, conversation_history=None)
+
+ assert all(len(m.get("message_uid", "")) == UID_LEN for m in messages)
+ stored = [r[0] for r in db._conn.execute(
+ "SELECT message_uid FROM messages WHERE session_id = ? AND active = 1 ORDER BY id", (sid,))]
+ assert [m["message_uid"] for m in messages] == stored
+
+
+def test_persist_override_keeps_the_uid(db):
+ """The ACP/gateway persist override rewrites the current-turn user CONTENT in place; the id is the row's."""
+ sid = "20260928_120200_override"
+ db.create_session(sid, "cli", model="test/model")
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ messages = [{"role": "user", "content": "api-only variant with injected context"}]
+ agent._persist_user_message_idx = 0
+ agent._persist_user_message_override = "what the user typed"
+ agent._persist_session(messages, conversation_history=None)
+ uid = messages[0]["message_uid"]
+
+ agent._apply_persist_user_message_override(messages)
+
+ assert messages[0]["content"] == "what the user typed"
+ assert messages[0]["message_uid"] == uid
+ row = db._conn.execute(
+ "SELECT content, message_uid FROM messages WHERE session_id = ? AND active = 1", (sid,)).fetchone()
+ assert (row[0], row[1]) == ("what the user typed", uid)
+
+
+def test_on_turn_complete_clones_carry_the_uid():
+ from agent.conversation_loop import _notify_context_engine_turn_complete
+
+ engine = _CapturingEngine()
+
+ class _Agent:
+ context_compressor = engine
+ session_id = "s"
+
+ messages = [{"role": "user", "content": "q", "message_uid": "a" * UID_LEN},
+ {"role": "assistant", "content": "r", "message_uid": "b" * UID_LEN}]
+ _notify_context_engine_turn_complete(_Agent(), messages, usage=None, logger=logging.getLogger("t"))
+
+ seen = engine.turn_complete_messages
+ assert [m["message_uid"] for m in seen] == ["a" * UID_LEN, "b" * UID_LEN]
+ assert all(clone is not original for clone, original in zip(seen, messages))
+
+
+def test_consecutive_user_merge_keeps_the_first_uid_and_records_the_absorbed_ones():
+ from agent.agent_runtime_helpers import _merge_consecutive_users
+
+ a = {"role": "user", "content": "first", "message_uid": "a" * UID_LEN}
+ b = {"role": "user", "content": "second", "message_uid": "b" * UID_LEN}
+ c = {"role": "user", "content": "third", "message_uid": "c" * UID_LEN}
+
+ merged, repairs = _merge_consecutive_users([a, b, c])
+
+ assert repairs == 2 and merged == [a]
+ assert a["content"] == "first\n\nsecond\n\nthird"
+ assert a["message_uid"] == "a" * UID_LEN
+ assert a["_absorbed_message_uids"] == ["b" * UID_LEN, "c" * UID_LEN]
+ # A restored (no ``_row_id``) absorbed dict still leaves its uid on the survivor.
+ assert "_absorbed_row_ids" not in a
+
+
+def test_the_uid_never_reaches_the_provider_copy():
+ from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
+
+ assert {"message_uid", "_absorbed_message_uids"} <= PERSISTENCE_ONLY_MESSAGE_FIELDS
diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.py
new file mode 100644
index 00000000000..11b86f3964f
--- /dev/null
+++ b/tests/hermes_state/test_message_uid.py
@@ -0,0 +1,206 @@
+"""``messages.message_uid``: a durable per-message id that survives every host copy path.
+
+The physical ``id`` is re-issued by every copy (in-place compaction generation, rotation child,
+concurrent-tail clone, ``replace_messages``), and ``_row_id`` is opt-in on restore. A consumer that
+keys on messages across restarts and boundaries (a context engine plugin) therefore had nothing
+stable to key on and re-identified rows by content and timestamp. ``message_uid`` is minted once at
+the row's first insert, stamped on the caller's dict, restored unconditionally, copied by every
+clone, kept by every re-insert of the same dict and left alone by row-addressed rewrites.
+"""
+
+from __future__ import annotations
+
+import copy
+import re
+
+import pytest
+
+from hermes_state import SessionDB
+
+UID_RE = re.compile(r"^[0-9a-f]{32}$")
+
+
+def db(tmp_path):
+ handle = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ yield handle
+ finally:
+ handle.close()
+
+
+def _rows(db, sid, *, active_only=True, include_session=False):
+ clause = " AND active = 1" if active_only else ""
+ cols = "id, session_id, role, content, message_uid, active, compacted"
+ return [dict(r) for r in db._conn.execute(
+ f"SELECT {cols} FROM messages WHERE session_id = ?{clause} ORDER BY id", (sid,)).fetchall()]
+
+
+def _seed(db, sid, n=4):
+ db.create_session(sid, "cli", model="m")
+ for i in range(n):
+ db.append_message(session_id=sid, role="user" if i % 2 == 0 else "assistant", content=f"msg {i}")
+ return _rows(db, sid)
+
+
+class TestMintAndRestore:
+ def test_fresh_store_carries_the_column_at_schema_v31(self, db):
+ cols = {r[1] for r in db._conn.execute("PRAGMA table_info(messages)").fetchall()}
+ assert "message_uid" in cols
+ assert db._conn.execute("SELECT version FROM schema_version").fetchone()[0] >= 31
+
+ def test_insert_mints_a_uid_and_stamps_the_callers_dict(self, db):
+ db.create_session("s", "cli")
+ msgs = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}]
+ db.append_messages_batch("s", msgs)
+ stored = _rows(db, "s")
+ assert [r["message_uid"] for r in stored] == [m["message_uid"] for m in msgs]
+ assert all(UID_RE.match(r["message_uid"]) for r in stored)
+ assert len({r["message_uid"] for r in stored}) == 2
+
+ def test_uid_is_per_occurrence_not_derived_from_content_or_time(self, db):
+ db.create_session("s", "cli")
+ twins = [{"role": "user", "content": "ok", "timestamp": 1_700_000_000.5},
+ {"role": "user", "content": "ok", "timestamp": 1_700_000_000.5}]
+ db.append_messages_batch("s", twins)
+ assert twins[0]["message_uid"] != twins[1]["message_uid"]
+
+ def test_restore_carries_the_uid_without_include_row_ids(self, db):
+ stored = _seed(db, "s")
+ # The ACP / gateway / compression-adoption shape: no ``include_row_ids``.
+ restored = db.get_messages_as_conversation("s", repair_alternation=True)
+ assert "_row_id" not in restored[0]
+ assert [m["message_uid"] for m in restored] == [r["message_uid"] for r in stored]
+ # And every other projection (display resume, lineage) agrees.
+ model_history, display_history = db.get_resume_conversations("s")
+ assert [m["message_uid"] for m in model_history] == [r["message_uid"] for r in stored]
+ assert [m["message_uid"] for m in display_history] == [r["message_uid"] for r in stored]
+
+ def test_an_explicit_uid_on_the_dict_is_written_not_replaced(self, db):
+ db.create_session("s", "cli")
+ msg = {"role": "user", "content": "q", "message_uid": "0" * 32}
+ db.append_messages_batch("s", [msg])
+ assert _rows(db, "s")[0]["message_uid"] == "0" * 32
+
+ def test_legacy_rows_are_backfilled_once_on_open(self, tmp_path):
+ path = tmp_path / "legacy.db"
+ first = SessionDB(db_path=path)
+ try:
+ _seed(first, "s")
+ # Rows written by a build that predates the column: NULL uid, schema behind v31.
+ first._conn.execute("UPDATE messages SET message_uid = NULL")
+ first._conn.execute("UPDATE schema_version SET version = 30")
+ first._conn.commit()
+ finally:
+ first.close()
+ second = SessionDB(db_path=path)
+ try:
+ uids = [r["message_uid"] for r in _rows(second, "s")]
+ assert all(u and UID_RE.match(u) for u in uids)
+ assert len(set(uids)) == len(uids)
+ assert second._conn.execute("SELECT version FROM schema_version").fetchone()[0] >= 31
+ # Idempotent: a second open keeps the backfilled values.
+ second.close()
+ third = SessionDB(db_path=path)
+ try:
+ assert [r["message_uid"] for r in _rows(third, "s")] == uids
+ finally:
+ third.close()
+ finally:
+ second.close()
+
+
+class TestCopyPathsKeepTheUid:
+ def test_in_place_compaction_keeps_uids_on_the_new_generation_and_the_tail_clone(self, db):
+ stored = _seed(db, "s", n=4)
+ watermark = stored[-1]["id"]
+ # Concurrent appends after the compressor captured its watermark.
+ db.append_message(session_id="s", role="user", content="late user")
+ db.append_message(session_id="s", role="assistant", content="late assistant")
+ late = _rows(db, "s")[4:]
+ restored = db.get_messages_as_conversation("s")
+ # The compressor's output: a summary the ENGINE already identified plus marker-swept COPIES of the
+ # kept tail (an engine may pre-mint its own rows' uids; the host writes them as given).
+ compacted = [{"role": "user", "content": "[CONTEXT COMPACTION] summary", "message_uid": "e" * 32},
+ copy.copy(restored[2]), copy.copy(restored[3])]
+ db.archive_and_compact("s", compacted, watermark=watermark)
+ active = _rows(db, "s")
+ assert [r["content"] for r in active] == [
+ "[CONTEXT COMPACTION] summary", "msg 2", "msg 3", "late user", "late assistant"]
+ # New generation: the copies keep the archived originals' uids; the clone keeps the late rows' uids.
+ assert [r["message_uid"] for r in active[1:3]] == [stored[2]["message_uid"], stored[3]["message_uid"]]
+ assert [r["message_uid"] for r in active[3:]] == [r["message_uid"] for r in late]
+ assert active[0]["message_uid"] == compacted[0]["message_uid"] == "e" * 32
+ # The physical ids DID change (that is the whole point), the archived originals keep theirs too.
+ assert {r["id"] for r in active}.isdisjoint({r["id"] for r in stored} | {r["id"] for r in late})
+ archived = [r for r in _rows(db, "s", active_only=False) if not r["active"]]
+ assert [r["message_uid"] for r in archived] == [r["message_uid"] for r in stored + late]
+
+ def test_rotation_child_keeps_uids_on_handoff_copies_and_the_foreign_tail_clone(self, db):
+ stored = _seed(db, "parent", n=2)
+ watermark = stored[-1]["id"]
+ db.append_message(session_id="parent", role="user", content="foreign append")
+ foreign = _rows(db, "parent")[2]
+ restored = db.get_messages_as_conversation("parent")
+ handoff = [{"role": "user", "content": "[CONTEXT COMPACTION] summary", "message_uid": "e" * 32},
+ copy.copy(restored[1])]
+ db.publish_compression_child(
+ parent_session_id="parent", child_session_id="child", source="cli", messages=handoff,
+ require_compression_lease=False, watermark=watermark, watermark_ceiling=foreign["id"])
+ child = _rows(db, "child")
+ assert [r["content"] for r in child] == ["[CONTEXT COMPACTION] summary", "msg 1", "foreign append"]
+ assert child[1]["message_uid"] == stored[1]["message_uid"]
+ assert child[2]["message_uid"] == foreign["message_uid"]
+ assert child[0]["message_uid"] == "e" * 32
+ # A restore of the child (what the resumed agent sees) carries the same uids.
+ assert [m["message_uid"] for m in db.get_messages_as_conversation("child")] == [
+ r["message_uid"] for r in child]
+
+ def test_replace_messages_keeps_uids_on_the_kept_prefix_and_the_reissued_rows(self, db):
+ stored = _seed(db, "s", n=4)
+ restored = db.get_messages_as_conversation("s")
+ # ACP non-owning persist / gateway rewrite: DELETE every active row and re-INSERT the history.
+ db.replace_messages("s", restored + [{"role": "user", "content": "new"}], active_only=True)
+ reissued = _rows(db, "s")
+ assert [r["message_uid"] for r in reissued[:4]] == [r["message_uid"] for r in stored]
+ assert reissued[4]["message_uid"] and reissued[4]["message_uid"] not in {r["message_uid"] for r in stored}
+ assert {r["id"] for r in reissued[:4]}.isdisjoint({r["id"] for r in stored})
+ # Rewind-style replace: the matched live prefix keeps its rows AND stamps their uids on the dicts.
+ prefix = [{"role": m["role"], "content": m["content"]} for m in restored[:2]]
+ db.replace_messages("s", prefix + [{"role": "user", "content": "edited"}], archive_dropped=True)
+ assert [m["message_uid"] for m in prefix] == [r["message_uid"] for r in reissued[:2]]
+ assert [r["message_uid"] for r in _rows(db, "s")[:2]] == [r["message_uid"] for r in reissued[:2]]
+
+ def test_row_addressed_rewrite_keeps_the_uid(self, db):
+ db.create_session("s", "cli")
+ msg = {"role": "user", "content": "api variant of the prompt"}
+ db.append_messages_batch("s", [msg])
+ before = _rows(db, "s")[0]
+ # The persist override / sanitizer rewrite: same dict, same row id and digest, new content.
+ msg["content"] = "clean prompt"
+ db.append_messages_batch("s", [msg])
+ after = _rows(db, "s")
+ assert len(after) == 1 and after[0]["id"] == before["id"]
+ assert after[0]["content"] == "clean prompt"
+ assert after[0]["message_uid"] == before["message_uid"] == msg["message_uid"]
+
+ def test_rewrite_adopts_the_stored_uid_onto_a_dict_that_lacks_one(self, db):
+ db.create_session("s", "cli")
+ msg = {"role": "user", "content": "prompt"}
+ db.append_messages_batch("s", [msg])
+ stored_uid = msg.pop("message_uid")
+ msg["content"] = "prompt (edited)"
+ db.append_messages_batch("s", [msg])
+ assert msg["message_uid"] == stored_uid
+ assert [r["message_uid"] for r in _rows(db, "s")] == [stored_uid]
+
+ def test_export_import_round_trip_keeps_the_uid(self, db, tmp_path):
+ stored = _seed(db, "s", n=3)
+ payload = db.export_session("s")
+ assert [m["message_uid"] for m in payload["messages"]] == [r["message_uid"] for r in stored]
+ other = SessionDB(db_path=tmp_path / "other.db")
+ try:
+ assert other.import_sessions([payload])["ok"]
+ assert [r["message_uid"] for r in _rows(other, "s")] == [r["message_uid"] for r in stored]
+ finally:
+ other.close()
diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.md
index d124ce46d9b..3135e59aea2 100644
--- a/website/docs/developer-guide/context-engine-plugin.md
+++ b/website/docs/developer-guide/context-engine-plugin.md
@@ -135,6 +135,49 @@ Contract:
- **Ordering / cache stability.** The hook runs **before** prompt cache-control and every request sanitizer, so (a) a replacement still passes the same validation as any request, and (b) the no-op default leaves the request byte-identical — prompt-cache behaviour is unchanged for non-implementing engines. An engine that replaces the list changes only its own cache prefix. Evaluated per provider request (re-runs on retries).
- **`on_turn_complete()`** is post-turn observation only; treat `messages` as read-only. **Coverage is best-effort:** it fires from the standard turn-finalization seam. Some abnormal early-return paths in the loop (e.g. a content-policy block or a provider terminal failure) persist and return without routing through finalization, so they do not currently emit this hook — treat it as a best-effort observation for completed turns, not a guaranteed callback for every early exit. Unifying all terminal paths behind one finalization seam is a separate follow-up.
+### Stable message identity: `message_uid`
+
+Every message the host has persisted carries `message_uid`: a 32-hex id
+(`uuid4().hex`) minted once, at the row's first insert, and stored in
+`messages.message_uid`. It is the key to use when an engine keeps its own
+per-message state (a verbatim store, a summary DAG, per-message embeddings)
+and needs to recognise a message it has already seen. The physical row id
+(`_row_id`) is not that key: it is re-issued by every copy and only present on
+some restore paths.
+
+What the host guarantees:
+
+- **Present on every engine surface** once a row exists: the `compress()`
+ input list, `on_turn_complete()` clones, `post_llm_call`'s
+ `conversation_history`, `on_session_end()` messages, and every restored
+ history (CLI, TUI, ACP, gateway, compression's durable-snapshot adoption). It
+ is restored unconditionally, unlike `_row_id`.
+- **Kept across every host copy of the same logical message:** in-place
+ compaction generations and their concurrent-tail clones, rotation-child
+ handoff copies and foreign-tail clones, `replace_messages` re-issues,
+ rewind, export/import.
+- **Kept across content rewrites of the same row:** the persist override, the
+ 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.
+- **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.
+- **Never on the wire.** `message_uid` and `_absorbed_message_uids` are in
+ `PERSISTENCE_ONLY_MESSAGE_FIELDS`: stripped from every outgoing provider
+ copy and ignored by the token estimator. Engines that never read them are
+ unaffected.
+- **Absent only before the row exists.** The current turn's user message has
+ no uid during a preflight `compress()` that runs before the turn-start
+ flush; the same dict object receives it at that flush. Stores upgraded from
+ an older schema backfill a uid onto every existing row once (schema v31);
+ rows written afterwards by an older build stay `NULL` until re-inserted.
+
### When to use these hooks — and when NOT to
- **Implement `select_context()` only when your engine must *replace* the
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 62070cfe205..5303ff43ff3 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`, and `display_metadata`:
+`display_kind`, `display_metadata`, and `message_uid`:
```sql
CREATE TABLE IF NOT EXISTS messages (
@@ -242,6 +242,7 @@ Notes:
- A reasoning-only clean stop (empty `content`, `finish_reason=stop`, reasoning present) is answered with the reasoning text, but the assistant row is never written with that text as `content`: `content` stays empty, the text lives in `reasoning`/`reasoning_content`, and `api_content` carries it so the next request replays the answer byte-identically. History surfaces therefore show it as reasoning, not as a reply.
- `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).
### FTS5 Full-Text Search
@@ -264,7 +265,7 @@ indexed columns — see `SCHEMA_SQL` in `hermes_state_common.py` for the exact S
## Schema Version and Migrations
-Current schema version: **23**
+Current schema version: **31**
The `schema_version` table stores a single integer. Simple column additions are handled declaratively by `_reconcile_columns()` (which diffs live columns against `SCHEMA_SQL` and ADDs any missing ones). The version-gated chain is reserved for data migrations and index/FTS changes that can't be expressed declaratively:
@@ -288,6 +289,7 @@ The `schema_version` table stores a single integer. Simple column additions are
| 23 | FTS storage redesign — external-content FTS tables replacing the v11 inline-mode copies (opt-in transition for existing DBs) |
| 29 | Cron sessions leave the trigram (substring/CJK) index; `messages_fts_trigram_src` view + triggers filter on `sessions.source`, one-time rebuild purges historical rows |
| 30 | Delegate-child (subagent) sessions leave the trigram index too — `source='subagent'` or the `$._delegate_from` marker (`FTS_TRIGRAM_SESSION_SQL`). Rows stay in `messages` and the standard `messages_fts` word index, so `session_search` still finds them; only the ~2.6× trigram shadow tables shrink. Same one-time rebuild as v29 |
+| 31 | `messages.message_uid` (declarative column add) plus a one-time backfill of a fresh uid onto every row that predates the column, so a v31 store hands every row to consumers with an id |
Versions not listed above were declarative column additions handled by `_reconcile_columns()` (version bump only, no data migration).