Skip to content

The agent that grows with you

fix(sessions): close the identity gaps the review found and prove the recovery paths

Evac2e2150d7844
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index e9bd1eb8bec..b7a6f6b5c50 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -19,7 +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, TOOL_CALL_UIDS
+from agent.message_metadata import TOOL_CALL_UIDS, record_absorbed_message
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
@@ -474,18 +474,7 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any]) ->
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)
+ record_absorbed_message(survivor, dropped)
def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 63e33b7e1ed..cb66f2bbd67 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -4869,6 +4869,10 @@ Write only the summary body. Do not include any preamble or prefix."""
"\n\n" + _INFLIGHT_TASK_REPLAY_HEADER + "\n" + task_text,
)
drop_stale_api_content(carrier)
+ # The carrier absorbed a durable user turn: record its uid (merge witness).
+ from agent.message_metadata import record_absorbed_message
+
+ record_absorbed_message(carrier, inflight)
return compressed
compressed.append(replay)
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index d980244b903..f832e65dd75 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -2426,6 +2426,11 @@ def _merge_anchor_into_user_message(target: dict, anchor: dict) -> None:
_replace_message_content(target, merged)
for flag in _SYNTHETIC_USER_FLAGS:
target.pop(flag, None)
+ # The anchor's text leads the composite, so the fold keeps the anchor's uid and records the
+ # scaffolding turn's (merge witness).
+ from agent.message_metadata import record_absorbed_message
+
+ record_absorbed_message(target, anchor, dropped_leads=True)
CompressedUserTurnOutcome = Literal["inserted", "merged", "already_present", "placeholder_appended"]
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 379adf45e26..ff8203b4e93 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -17,7 +17,7 @@ from typing import Any, Dict, List, Optional
from agent.codex_responses_adapter import _summarize_user_message_for_log
from agent.fast_mode import begin_turn as begin_fast_mode_turn
-from agent.message_metadata import append_message
+from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message
from agent.message_sanitization import _repair_tool_call_arguments, _sanitize_surrogates
from agent.model_metadata import MINIMUM_CONTEXT_LENGTH, _estimate_tools_tokens_rough
from agent.process_bootstrap import _install_safe_stdio
@@ -1316,7 +1316,16 @@ def _apply_context_engine_selection(
# Require a NON-EMPTY list of dicts: ``all([])`` is ``True``, so a ``[]`` from a
# buggy engine would otherwise replace the request instead of failing open.
if isinstance(selected, list) and selected and all(isinstance(m, dict) for m in selected):
- return selected
+ # The engine may hand back the ``conversation_messages`` clones (or its own dicts) that still
+ # carry persistence-only fields; the request copy was stripped BEFORE this hook, so strip the
+ # selection too or those fields reach the provider. Dicts without them pass through as-is.
+ if not any(key in m for m in selected for key in PERSISTENCE_ONLY_MESSAGE_FIELDS):
+ return selected
+ return [
+ {k: v for k, v in m.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}
+ if any(key in m for key in PERSISTENCE_ONLY_MESSAGE_FIELDS) else m
+ for m in selected
+ ]
logger.warning(
"Context engine select_context returned an invalid value "
"(not a non-empty list of dicts); ignoring (session=%s)", session_label,
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index f51cad36163..0d3eaba3d17 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from time import time as wall_time
-from typing import Any, MutableMapping, Optional, TypeVar
+from typing import Any, List, Mapping, MutableMapping, Optional, TypeVar
# These fields describe Hermes' durable record and timeline display, not
@@ -41,11 +41,60 @@ PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(
) | REPAIR_BOOKKEEPING_FIELDS
+def _uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:
+ uid = msg.get(MESSAGE_UID)
+ return uid if isinstance(uid, str) and uid else None
+
+
+def _absorbed_uids(msg: Mapping[str, Any]) -> List[str]:
+ return [u for u in (msg.get(ABSORBED_MESSAGE_UIDS) or ()) if isinstance(u, str) and u]
+
+
+def record_absorbed_message(
+ survivor: MutableMapping[str, Any], dropped: Mapping[str, Any], *, dropped_leads: bool = False,
+) -> None:
+ """Merge-witness bookkeeping for every host fold of *dropped* into *survivor*.
+
+ The composite keeps the uid of the constituent whose text comes first and records every other
+ constituent's uid in ``_absorbed_message_uids`` (text order, no repeats). By default the survivor's
+ text leads; with *dropped_leads* the dropped dict's text was put first (the real user anchor folded
+ into a scaffolding turn), so its uid becomes the survivor's and the survivor's former uid is recorded.
+ A dict without a uid (unflushed, scaffolding, engine-authored) contributes nothing; an empty result
+ leaves the survivor untouched.
+ """
+ survivor_uid = _uid_or_none(survivor)
+ dropped_uid = _uid_or_none(dropped)
+ if dropped_leads and dropped_uid:
+ survivor[MESSAGE_UID] = dropped_uid
+ ordered = _absorbed_uids(dropped) + ([survivor_uid] if survivor_uid else []) + _absorbed_uids(survivor)
+ else:
+ ordered = _absorbed_uids(survivor) + ([dropped_uid] if dropped_uid else []) + _absorbed_uids(dropped)
+ absorbed: List[str] = []
+ for uid in ordered:
+ if uid != survivor.get(MESSAGE_UID) and uid not in absorbed:
+ absorbed.append(uid)
+ if absorbed:
+ survivor[ABSORBED_MESSAGE_UIDS] = absorbed
+
+
+def _named_tool_call_variants(assistant: Any) -> List[str]:
+ """Every pairing-id variant of every tool call an assistant dict names."""
+ from agent.message_sanitization import tool_call_id_variants
+
+ if not isinstance(assistant, dict):
+ return []
+ return [variant for tc in assistant.get("tool_calls") or () for variant in tool_call_id_variants(tc)]
+
+
def index_tool_call_uids(index: MutableMapping[str, str], assistant: Any) -> None:
"""Register an assistant dict's ``_tool_call_uids`` under every pairing-id variant of its tool calls, so a
- later tool-result row can be resolved by any spelling of its ``tool_call_id``."""
+ later tool-result row can be resolved by any spelling of its ``tool_call_id``. Provider ids repeat, so
+ every id this assistant names first shadows an earlier occurrence's entry: a result pairs with the
+ NEAREST preceding call, and a call without a uid (a legacy row) pairs its result with nothing."""
from agent.message_sanitization import coalesce_tool_call_id, tool_call_id_variants
+ for variant in _named_tool_call_variants(assistant):
+ index.pop(variant, None)
uids = assistant.get(TOOL_CALL_UIDS) if isinstance(assistant, dict) else None
if not isinstance(uids, dict) or not uids:
return
@@ -78,15 +127,20 @@ def tool_call_uid_from_history(messages: Any, tool_index: int) -> Optional[str]:
tool_call_id = tool_msg.get("tool_call_id") if isinstance(tool_msg, dict) else None
if not isinstance(tool_call_id, str) or not tool_call_id:
return None
+ from agent.message_sanitization import tool_result_id_variants
+
+ result_variants = set(tool_result_id_variants(tool_call_id))
for prior in reversed(messages[:tool_index]):
- if isinstance(prior, dict) and prior.get("role") == "assistant" and prior.get(TOOL_CALL_UIDS):
- index: dict = {}
- index_tool_call_uids(index, prior)
- uid = resolve_tool_call_uid(index, tool_call_id)
- if uid:
- return uid
- elif isinstance(prior, dict) and prior.get("role") == "user":
+ if not isinstance(prior, dict):
+ continue
+ if prior.get("role") == "user":
return None # a tool result never pairs across a user turn
+ if prior.get("role") != "assistant" or result_variants.isdisjoint(_named_tool_call_variants(prior)):
+ continue
+ # The nearest assistant naming this id owns the result: its uid, or none if it has no map (legacy).
+ index: dict = {}
+ index_tool_call_uids(index, prior)
+ return resolve_tool_call_uid(index, tool_call_id)
return None
_Message = TypeVar("_Message", bound=MutableMapping[str, Any])
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index af858377d4e..5829c118984 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -11,6 +11,7 @@ import logging
import time
from typing import Any, Dict, List, Optional
+from agent.message_metadata import record_absorbed_message
from agent.model_metadata import estimate_messages_tokens_rough, estimate_tokens_rough
# Log name parity with the origin module.
@@ -508,6 +509,7 @@ class MicroCompactionMixin:
# as the defrag rewrite site above.
prev.pop(_cc()._DB_PERSISTED_MARKER, None)
self._flush_scan_cursor_invalidated = True
+ record_absorbed_message(prev, msg) # merge witness: prev keeps its uid, records msg's
else:
merged.append(msg)
return merged
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
index 3c7ffc48a15..3d60484821a 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -30,9 +30,11 @@ def _json_map(text: Any) -> Dict[str, str]:
# 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. ``message_uid``
-# is identity too: a rewrite changes the message's content, never which logical message the row is.
+# and a result row's ``tool_call_uid`` are identity too: a rewrite changes the message's content, never
+# which logical message (or which call occurrence) the row is. ``tool_call_uids`` IS payload: it follows
+# ``tool_calls`` (an assistant merge unions both), so it is rewritten with the row.
_NON_PAYLOAD_COLUMNS = frozenset(
- {"session_id", "role", "timestamp", "active", "display_identity", MESSAGE_UID, "tool_call_uids", "tool_call_uid"})
+ {"session_id", "role", "timestamp", "active", "display_identity", MESSAGE_UID, "tool_call_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
@@ -170,8 +172,10 @@ def resolve_and_repair_transcript_batch(
# 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]
- if final_row["tool_call_uids"]:
- msg[TOOL_CALL_UIDS] = _json_map(final_row["tool_call_uids"])
+ if stored_tool_uids := _json_map(final_row["tool_call_uids"]):
+ # Stored pairings win; pairings only the live list knows (an un-persisted merge's union) stay.
+ live_tool_uids = msg.get(TOOL_CALL_UIDS)
+ msg[TOOL_CALL_UIDS] = {**(live_tool_uids if isinstance(live_tool_uids, dict) else {}), **stored_tool_uids}
if final_row["tool_call_uid"]:
msg[TOOL_CALL_UID] = final_row["tool_call_uid"]
msg[DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 5419a5148cb..a6c456caef3 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -623,6 +623,14 @@ CREATE INDEX IF NOT EXISTS idx_messages_display_backfill
CREATE INDEX IF NOT EXISTS idx_messages_display_identity
ON messages(session_id, display_identity, display_order)
WHERE display_identity IS NOT NULL AND (active = 1 OR compacted = 1);
+-- Every row carries a message_uid, whoever wrote it: a build that predates the column inserts NULL, so the
+-- store mints one on its behalf (the current build always binds a uid, so this never fires for it).
+DROP TRIGGER IF EXISTS messages_message_uid_insert;
+CREATE TRIGGER IF NOT EXISTS messages_message_uid_insert
+AFTER INSERT ON messages WHEN new.message_uid IS NULL
+BEGIN
+ UPDATE messages SET message_uid = lower(hex(randomblob(16))) WHERE id = new.id;
+END;
DROP TRIGGER IF EXISTS messages_display_order_insert;
CREATE TRIGGER IF NOT EXISTS messages_display_order_insert
AFTER INSERT ON messages WHEN new.display_order IS NULL
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index afbe64b86fd..ace61671c0a 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -353,7 +353,9 @@ class SessionMessagesMixin:
uids[call_id] = uuid.uuid4().hex
if uids:
msg[TOOL_CALL_UIDS] = uids
- index_tool_call_uids(batch_index, msg)
+ index_tool_call_uids(batch_index, msg) # this row's ids shadow any earlier occurrence's
+ elif role == "user":
+ batch_index.clear() # a result never pairs across a user turn
elif role == "tool" and _tool_call_uid_or_none(msg) is None:
uid = resolve_tool_call_uid(batch_index, msg.get("tool_call_id"))
if uid:
@@ -1665,7 +1667,12 @@ class SessionMessagesMixin:
for col in ("reasoning_details", "codex_reasoning_items", "codex_message_items") if row[col])
if row["tool_call_uids"] and (tool_uids := _uid_map(row["tool_call_uids"])):
msg[TOOL_CALL_UIDS] = tool_uids
+ if msg.get("tool_calls"):
+ # Provider ids repeat: this row's calls shadow an earlier occurrence's entries, and a
+ # row without a map (an older writer's) leaves its results unpaired rather than mispaired.
index_tool_call_uids(tool_uid_index, msg)
+ elif row["role"] == "user":
+ tool_uid_index.clear() # a result never pairs across a user turn
elif row["role"] == "tool":
# The stored uid, else the one its assistant row named (a result appended by an older build
# or a lone append): rows are read in id order, so the call always precedes its result.
@@ -1872,7 +1879,7 @@ class SessionMessagesMixin:
if target_row.get("role") != "user":
raise ValueError(
f"rewind target must be a 'user' message (got role={target_row.get('role')!r}, id={target_message_id})")
- replacement_message_id = replacement = None
+ replacement_message_id = replacement_message_uid = replacement = None
if preserve_compaction_handoff or expected_target_content is not None:
replacement = self._split_rewind_target(target_row, expected_target_content, preserve_compaction_handoff)
ids = [r[0] for r in conn.execute("SELECT id FROM messages WHERE session_id = ? AND id >= ? AND active = 1",
@@ -1882,18 +1889,20 @@ class SessionMessagesMixin:
if replacement is not None:
self._insert_message_rows(conn, session_id, [replacement])
replacement_message_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
+ replacement_message_uid = _message_uid_or_none(replacement) # stamped by the insert
conn.execute(
"UPDATE sessions SET rewind_count = COALESCE(rewind_count, 0) + 1 WHERE id = ?", (session_id,))
message_count, tool_call_count = self._active_transcript_counts(conn, session_id)
conn.execute(f"{_SET_COUNTERS_SQL} WHERE id = ?", (message_count, tool_call_count, session_id))
head_id = conn.execute(
"SELECT MAX(id) FROM messages WHERE session_id = ? AND active = 1", (session_id,)).fetchone()[0]
- return target_row, ids, head_id, replacement_message_id
- target_row, rewound, new_head_id, replacement_message_id = self._execute_write(_do)
+ return target_row, ids, head_id, replacement_message_id, replacement_message_uid
+ target_row, rewound, new_head_id, replacement_message_id, replacement_message_uid = self._execute_write(_do)
# Decode for the prompt-buffer prefill without a second fallible DB operation.
target_row["content"] = self._decode_content(target_row.get("content"))
return {"rewound_count": len(rewound), "target_message": target_row, "new_head_id": new_head_id,
- **({"replacement_message_id": replacement_message_id} if preserve_compaction_handoff else {})}
+ **({"replacement_message_id": replacement_message_id,
+ "replacement_message_uid": replacement_message_uid} if preserve_compaction_handoff else {})}
def message_count(self, session_id: str = None) -> int:
"""Count messages, optionally for a specific session."""
diff --git a/hermes_state_rewind.py b/hermes_state_rewind.py
index 39f83777d26..c0619857fa2 100644
--- a/hermes_state_rewind.py
+++ b/hermes_state_rewind.py
@@ -111,7 +111,10 @@ class SessionRewindMixin:
replacement_id = result.get("replacement_message_id")
if not isinstance(replacement_id, int) or not durable_prefix:
raise RuntimeError("rewind did not retain its compaction handoff")
+ # The installed scaffold IS the replacement row: carry its identity, not just its row id.
durable_prefix[-1].update({"_row_id": replacement_id, _DB_PERSISTED_MARKER: True})
+ if isinstance(replacement_uid := result.get("replacement_message_uid"), str) and replacement_uid:
+ durable_prefix[-1]["message_uid"] = replacement_uid
prefix[-1] = durable_prefix[-1]
if adopt_row_ids and prefix is not durable_prefix and len(prefix) == len(durable_prefix) and all(
warm.get("role") == durable_message.get("role")
@@ -123,6 +126,8 @@ class SessionRewindMixin:
for warm, durable_message in zip(prefix, durable_prefix):
if isinstance(row_id := durable_message.get("_row_id"), int):
warm["_row_id"] = row_id
+ if isinstance(uid := durable_message.get("message_uid"), str) and uid:
+ warm["message_uid"] = uid
return RewindOutcome(
prefix=prefix, live_view=live_view,
live_text=live_text if live_text is not None else flatten_message_text(live_view.get("content")),
diff --git a/hermes_state_schema.py b/hermes_state_schema.py
index 9b1820b11b3..330e4dbc2bc 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -1051,14 +1051,19 @@ 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:
+ if current_version < 31 and cursor.execute(
+ "SELECT 1 FROM state_meta WHERE key = 'message_uid_backfill' LIMIT 1"
+ ).fetchone() is None:
# 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.
+ # (``_insert_message_rows``, or the ``messages_message_uid_insert`` trigger for an older
+ # writer); 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. Its own marker: a store whose schema_version cannot advance (no FTS5) must
+ # not repeat the full-table scan on every open.
cursor.execute(
"UPDATE messages SET message_uid = lower(hex(randomblob(16))) WHERE message_uid IS NULL"
)
+ self.set_meta("message_uid_backfill", "1", cursor=cursor)
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/acp_adapter/test_session.py b/tests/acp_adapter/test_session.py
index 917f95eea34..a34234f8ee9 100644
--- a/tests/acp_adapter/test_session.py
+++ b/tests/acp_adapter/test_session.py
@@ -3,6 +3,7 @@
import contextlib
import io
import json
+import re
from types import SimpleNamespace
import pytest
from unittest.mock import MagicMock, patch
@@ -543,6 +544,8 @@ class TestPersistence:
# Load-time durability stamp (#92231): rows materialized from the DB
# are marked persisted so a later flush can't re-append them.
assert msg.pop("_db_persisted", None) is True
+ # The durable per-message id rides on every restored row, like the timestamp.
+ assert re.fullmatch(r"[0-9a-f]{32}", msg.pop("message_uid", ""))
assert restored.history == [{
"role": "assistant",
"content": "hello",
diff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.py
index fd420d2a264..155733c2b61 100644
--- a/tests/agent/test_context_engine_message_uid.py
+++ b/tests/agent/test_context_engine_message_uid.py
@@ -112,6 +112,39 @@ def test_compress_input_after_a_cold_restore_carries_every_rows_uid(db):
assert [m.get("message_uid") for m in compressed] == [r["message_uid"] for r in active]
[email protected]("in_place", [True, False], ids=["in_place", "rotation"])
+def test_an_engine_authored_uid_survives_the_commit(db, in_place):
+ """An engine that pre-stamps ``message_uid`` on the rows it emits gets that value written through the
+ commit (in place and on rotation), so it can recognise its own rows by uid afterwards."""
+ from agent.conversation_compression import compress_context
+
+ class _PreStamping(_CapturingEngine):
+ def compress(self, messages, current_tokens=None, focus_topic=None, force=False):
+ summary = {"role": "user", "content": "[CONTEXT COMPACTION] summary of prior turns",
+ "message_uid": "e" * UID_LEN}
+ return [summary] + [dict(m) for m in messages[-2:]]
+
+ sid = f"20260928_120050_{'inplace' if in_place else 'rotate'}"
+ stored = _seed(db, sid)
+ restored = db.get_messages_as_conversation(sid)
+ agent = _make_agent(db, sid)
+ agent.context_compressor = _PreStamping()
+ agent.compression_in_place = in_place
+ 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")
+
+ committed_sid = agent.session_id
+ if not in_place:
+ assert committed_sid != sid # rotation published a child session
+ active = db.get_messages_as_conversation(committed_sid)
+ assert [m["content"] for m in active][:1] == ["[CONTEXT COMPACTION] summary of prior turns"]
+ assert active[0]["message_uid"] == "e" * UID_LEN
+ assert [m["message_uid"] for m in active[1:3]] == [stored[4]["message_uid"], stored[5]["message_uid"]]
+ assert [m.get("message_uid") for m in compressed[:3]] == [m["message_uid"] for m in active[:3]]
+
+
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."""
@@ -235,6 +268,25 @@ def test_tool_result_flushed_after_its_call_pairs_through_the_live_list(db):
assert stored == uid
+def test_the_live_list_walk_binds_a_result_to_the_nearest_call_that_names_it():
+ from agent.message_metadata import tool_call_uid_from_history
+
+ def call(uid=None):
+ msg = {"role": "assistant", "content": "",
+ "tool_calls": [{"id": "call_x", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}
+ if uid:
+ msg["_tool_call_uids"] = {"call_x": uid}
+ return msg
+
+ result = {"role": "tool", "content": "r", "tool_call_id": "call_x"}
+ # Nearest call wins over an older one with the same provider id.
+ assert tool_call_uid_from_history([call("1" * UID_LEN), result, call("2" * UID_LEN), result], 3) == "2" * UID_LEN
+ # A nearer call without a map (legacy) owns the result: no uid, never the older occurrence's.
+ assert tool_call_uid_from_history([call("1" * UID_LEN), result, call(), result], 3) is None
+ # Never across a user turn.
+ assert tool_call_uid_from_history([call("1" * UID_LEN), {"role": "user", "content": "q"}, result], 2) is None
+
+
def test_assistant_merge_keeps_the_absorbed_turns_tool_call_uids():
from agent.agent_runtime_helpers import _merge_consecutive_assistants
@@ -253,3 +305,120 @@ def test_the_uid_never_reaches_the_provider_copy():
from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
assert {"message_uid", "_absorbed_message_uids", "_tool_call_uids", "_tool_call_uid"} <= PERSISTENCE_ONLY_MESSAGE_FIELDS
+
+
+def test_a_select_context_selection_is_stripped_before_the_provider():
+ """The request copy is stripped BEFORE ``select_context``; an engine that hands back the
+ ``conversation_messages`` clones must not put the ids back on the wire."""
+ from agent.conversation_loop import _apply_context_engine_selection
+ from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
+
+ class _Selecting(_CapturingEngine):
+ def select_context(self, api_messages, conversation_messages=None, incoming_message=None, budget_tokens=0):
+ return list(conversation_messages)
+
+ class _Agent:
+ context_compressor = _Selecting()
+ session_id = "s"
+
+ history = [
+ {"role": "user", "content": "q", "message_uid": "a" * UID_LEN, "timestamp": 1.0, "_row_id": 1,
+ "_absorbed_message_uids": ["b" * UID_LEN]},
+ {"role": "assistant", "content": "", "message_uid": "c" * UID_LEN, "timestamp": 2.0,
+ "tool_calls": [{"id": "call_x", "type": "function", "function": {"name": "t", "arguments": "{}"}}],
+ "_tool_call_uids": {"call_x": "d" * UID_LEN}},
+ {"role": "tool", "content": "r", "tool_call_id": "call_x", "message_uid": "e" * UID_LEN, "timestamp": 3.0,
+ "_tool_call_uid": "d" * UID_LEN},
+ ]
+ api = [{k: v for k, v in m.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS} for m in history]
+
+ out = _apply_context_engine_selection(_Agent(), api, history, history[0], logger=logging.getLogger("t"))
+
+ assert [m["content"] for m in out] == ["q", "", "r"]
+ assert out[1]["tool_calls"][0]["id"] == "call_x"
+ assert not any(key in m for m in out for key in PERSISTENCE_ONLY_MESSAGE_FIELDS)
+ assert all(m["message_uid"] for m in history) # history untouched
+
+
+def test_the_inflight_task_restated_onto_the_carrier_records_its_uid():
+ from agent.context_compressor import (
+ COMPRESSED_SUMMARY_METADATA_KEY, SUMMARY_PREFIX, _INFLIGHT_TASK_REPLAY_HEADER, _SUMMARY_END_MARKER,
+ ContextCompressor,
+ )
+
+ compressor = object.__new__(ContextCompressor)
+ compressor.quiet_mode = True
+ carrier = {"role": "user", "content": f"{SUMMARY_PREFIX}\n\nwhat happened\n\n{_SUMMARY_END_MARKER}",
+ COMPRESSED_SUMMARY_METADATA_KEY: True, "message_uid": "s" * UID_LEN}
+ inflight = {"role": "user", "content": "finish the task", "message_uid": "a" * UID_LEN}
+
+ out = compressor._reappend_inflight_user_task([carrier], inflight)
+
+ assert out == [carrier] and _INFLIGHT_TASK_REPLAY_HEADER in carrier["content"]
+ assert carrier["message_uid"] == "s" * UID_LEN
+ assert carrier["_absorbed_message_uids"] == ["a" * UID_LEN]
+
+
+def test_the_real_user_anchor_folded_into_scaffolding_keeps_the_anchors_uid():
+ """The anchor's text leads the composite, so its uid is the composite's; the scaffolding row's is absorbed."""
+ from agent.conversation_compression import _insert_real_user_anchor, _merge_anchor_into_user_message
+
+ target = {"role": "user", "content": "[todo snapshot]", "message_uid": "t" * UID_LEN}
+ anchor = {"role": "user", "content": "the real ask", "message_uid": "a" * UID_LEN,
+ "_absorbed_message_uids": ["b" * UID_LEN]}
+ _merge_anchor_into_user_message(target, anchor)
+ assert target["content"] == "the real ask\n\n[todo snapshot]"
+ assert target["message_uid"] == "a" * UID_LEN
+ assert target["_absorbed_message_uids"] == ["b" * UID_LEN, "t" * UID_LEN]
+
+ # Never-persisted scaffolding (no uid) absorbs nothing but still takes the anchor's identity.
+ compressed = [{"role": "user", "content": "earlier"}, {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "[todo snapshot]"}]
+ assert _insert_real_user_anchor(compressed, dict(anchor, _absorbed_message_uids=[])) == "merged"
+ assert compressed[-1]["message_uid"] == "a" * UID_LEN
+ assert "_absorbed_message_uids" not in compressed[-1]
+
+
+def test_micro_compactions_adjacent_user_merge_records_the_witness():
+ from types import SimpleNamespace
+
+ from agent.micro_compaction import MicroCompactionMixin
+
+ first = {"role": "user", "content": "one", "message_uid": "1" * UID_LEN}
+ second = {"role": "user", "content": "two", "message_uid": "2" * UID_LEN}
+ merged = MicroCompactionMixin._merge_adjacent_user_turns(SimpleNamespace(), [first, second])
+
+ assert merged == [first] and first["content"] == "one\n\ntwo"
+ assert first["message_uid"] == "1" * UID_LEN
+ assert first["_absorbed_message_uids"] == ["2" * UID_LEN]
+
+
+def test_an_assistant_merge_rewrite_persists_the_unioned_tool_call_uids(db):
+ """Alternation repair unions two flushed assistant turns' tool calls; the survivor's row-addressed
+ rewrite must carry the unioned uid map (it follows ``tool_calls``), and a restore must return it."""
+ from agent.agent_runtime_helpers import repair_message_sequence
+
+ sid = "20260928_120500_union"
+ db.create_session(sid, "cli", model="test/model")
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ survivor = {"role": "assistant", "content": "let me check"}
+ caller = {"role": "assistant", "content": "",
+ "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}
+ result = {"role": "tool", "content": "r", "tool_call_id": "call_2", "tool_name": "t"}
+ messages = [{"role": "user", "content": "q"}, survivor, caller, result]
+ agent._persist_user_message_idx = 0
+ agent._persist_session(messages, conversation_history=None) # both assistants flushed with a digest
+ uids = dict(caller["_tool_call_uids"])
+ assert set(uids) == {"call_2"} and "_tool_call_uids" not in survivor and result["_tool_call_uid"] == uids["call_2"]
+
+ repair_message_sequence(agent, messages)
+ assert messages == [messages[0], survivor, result] and survivor["_tool_call_uids"] == uids
+ agent._persist_session(messages, conversation_history=None)
+
+ assert survivor["_tool_call_uids"] == uids
+ again = db.get_messages_as_conversation(sid, repair_alternation=False)
+ stored = next(m for m in again if m["role"] == "assistant" and m["content"].startswith("let me check"))
+ assert [tc["id"] for tc in stored["tool_calls"]] == ["call_2"]
+ assert stored["_tool_call_uids"] == uids
+ assert next(m for m in again if m["role"] == "tool")["_tool_call_uid"] == uids["call_2"]
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index d3501b86ef0..364ea288ac7 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -2660,3 +2660,38 @@ def test_run_backup_prunes_older_default_named_zips_but_not_others(tmp_path, mon
kept = sorted(p.name for p in tmp_path.glob("hermes-backup-*.zip"))
assert len(kept) == 2 and kept[0] == "hermes-backup-2026-01-04-000000.zip"
assert (tmp_path / "my-archive.zip").exists()
+
+
+def test_import_restores_the_session_store_with_its_message_uids(tmp_path, monkeypatch):
+ """A backup ships state.db as a SQLite snapshot and an import puts it back byte-for-byte: the durable
+ message ids come back with the rows."""
+ from hermes_state import SessionDB
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ _make_hermes_tree(hermes_home)
+ db = SessionDB(db_path=hermes_home / "state.db")
+ try:
+ db.create_session("s", "cli", model="m")
+ db.append_message(session_id="s", role="user", content="q")
+ db.append_message(session_id="s", role="assistant", content="a")
+ uids = [m["message_uid"] for m in db.get_messages_as_conversation("s")]
+ finally:
+ db.close()
+ assert len(uids) == 2 and all(len(u) == 32 for u in uids)
+
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ from hermes_cli.backup import run_backup, run_import
+
+ out_zip = tmp_path / "backup.zip"
+ run_backup(Namespace(output=str(out_zip)))
+ for name in ("state.db", "state.db-wal", "state.db-shm"):
+ (hermes_home / name).unlink(missing_ok=True)
+ assert run_import(Namespace(zipfile=str(out_zip), force=True)) is None
+
+ restored = SessionDB(db_path=hermes_home / "state.db")
+ try:
+ assert [m["message_uid"] for m in restored.get_messages_as_conversation("s")] == uids
+ finally:
+ restored.close()
diff --git a/tests/hermes_cli/test_session_recovery.py b/tests/hermes_cli/test_session_recovery.py
index 90d78a9d311..da73486843c 100644
--- a/tests/hermes_cli/test_session_recovery.py
+++ b/tests/hermes_cli/test_session_recovery.py
@@ -935,3 +935,42 @@ def test_salvage_bounds_damaged_low_edge_from_the_aggregate_not_the_int64_domain
assert result["range_queries"] < 200
# Only the rows on the damaged leaf are lost; everything behind it is recovered.
assert result["copied_rows"] >= 180 - 60
+
+
+def test_recover_carries_message_identity_columns(tmp_path):
+ """``hermes sessions recover`` copies the compatible columns of ``messages`` into a current-schema
+ database: the durable ids (``message_uid``, the merge witness, the tool-call uids) survive with the rows."""
+ source = tmp_path / "source.db"
+ db = SessionDB(db_path=source)
+ try:
+ db.create_session("s", "cli", model="m")
+ db.append_message(session_id="s", role="user", content="q")
+ db._conn.execute("UPDATE messages SET absorbed_message_uids = ? WHERE content = 'q'", (json.dumps(["b" * 32]),))
+ db._conn.commit()
+ db.append_message(
+ session_id="s", role="assistant", content="",
+ tool_calls=[{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}])
+ db.append_message(session_id="s", role="tool", content="r", tool_call_id="call_1", tool_name="t")
+ expected = [dict(r) for r in db._conn.execute(
+ "SELECT role, message_uid, absorbed_message_uids, tool_call_uids, tool_call_uid "
+ "FROM messages WHERE session_id = 's' ORDER BY id")]
+ finally:
+ db.close()
+ assert all(len(r["message_uid"]) == 32 for r in expected)
+
+ output = tmp_path / "recovered.db"
+ report = recover_session_database(source, output, work_dir=tmp_path)
+ assert report["complete"] is True
+
+ recovered = SessionDB(db_path=output)
+ try:
+ got = [dict(r) for r in recovered._conn.execute(
+ "SELECT role, message_uid, absorbed_message_uids, tool_call_uids, tool_call_uid "
+ "FROM messages WHERE session_id = 's' ORDER BY id")]
+ assert got == expected
+ restored = recovered.get_messages_as_conversation("s")
+ assert [m["message_uid"] for m in restored] == [r["message_uid"] for r in expected]
+ assert restored[0]["_absorbed_message_uids"] == ["b" * 32]
+ assert restored[2]["_tool_call_uid"] == restored[1]["_tool_call_uids"]["call_1"]
+ finally:
+ recovered.close()
diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.py
index cbbd3377875..2803bdfe62a 100644
--- a/tests/hermes_state/test_message_uid.py
+++ b/tests/hermes_state/test_message_uid.py
@@ -11,6 +11,7 @@ clone, kept by every re-insert of the same dict and left alone by row-addressed
from __future__ import annotations
import copy
+import json
import re
import pytest
@@ -87,9 +88,10 @@ class TestMintAndRestore:
first = SessionDB(db_path=path)
try:
_seed(first, "s")
- # Rows written by a build that predates the column: NULL uid, schema behind v31.
+ # Rows written by a build that predates the column: NULL uid, schema behind v31, no marker.
first._conn.execute("UPDATE messages SET message_uid = NULL")
first._conn.execute("UPDATE schema_version SET version = 30")
+ first._conn.execute("DELETE FROM state_meta WHERE key = 'message_uid_backfill'")
first._conn.commit()
finally:
first.close()
@@ -99,6 +101,7 @@ class TestMintAndRestore:
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
+ assert second.get_meta("message_uid_backfill") == "1"
# Idempotent: a second open keeps the backfilled values.
second.close()
third = SessionDB(db_path=path)
@@ -109,6 +112,35 @@ class TestMintAndRestore:
finally:
second.close()
+ def test_the_backfill_marker_gates_the_scan_when_the_version_cannot_advance(self, tmp_path):
+ """A store whose schema_version stays behind (no FTS5) must not rescan on every open: the marker,
+ not the version, says the one-time backfill ran."""
+ path = tmp_path / "marked.db"
+ first = SessionDB(db_path=path)
+ try:
+ _seed(first, "s")
+ first._conn.execute("UPDATE messages SET message_uid = NULL")
+ first._conn.execute("UPDATE schema_version SET version = 30")
+ first.set_meta("message_uid_backfill", "1")
+ finally:
+ first.close()
+ second = SessionDB(db_path=path)
+ try:
+ assert [r["message_uid"] for r in _rows(second, "s")] == [None] * 4
+ finally:
+ second.close()
+
+ def test_a_row_inserted_without_a_uid_by_an_older_writer_gets_one(self, db):
+ """The store mints for a build that predates the column (its INSERT binds no uid)."""
+ db.create_session("s", "cli", model="test/model")
+ db._conn.execute(
+ "INSERT INTO messages (session_id, role, content, timestamp) VALUES ('s', 'user', 'old writer', 1.0)"
+ )
+ db._conn.commit()
+ uid = db._conn.execute("SELECT message_uid FROM messages WHERE content = 'old writer'").fetchone()[0]
+ assert uid and UID_RE.match(uid)
+ assert db.get_messages_as_conversation("s")[0]["message_uid"] == uid
+
class TestCopyPathsKeepTheUid:
def test_in_place_compaction_keeps_uids_on_the_new_generation_and_the_tail_clone(self, db):
@@ -293,6 +325,111 @@ class TestPersistedMergeWitness:
finally:
other.close()
+ def test_a_reused_provider_id_pairs_with_the_nearest_call_only(self, db):
+ """Provider ids repeat: on restore a result binds to the NEAREST preceding call; a legacy call row
+ without a map (an older writer's) leaves its result unpaired instead of inheriting an older uid, and
+ nothing pairs across a user turn."""
+ sid = "s"
+ db.create_session(sid, "cli", model="m")
+ call = [{"id": "call_x", "type": "function", "function": {"name": "t", "arguments": "{}"}}]
+ db.append_message(session_id=sid, role="user", content="q1")
+ db.append_message(session_id=sid, role="assistant", content="", tool_calls=call)
+ db.append_message(session_id=sid, role="tool", content="r1", tool_call_id="call_x", tool_name="t")
+ db.append_message(session_id=sid, role="user", content="q2")
+ # An older writer's rows: same provider id, no uid map on the call, no uid on the result.
+ db._conn.execute(
+ "INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES (?, 'assistant', '', ?, 5.0)",
+ (sid, json.dumps(call)))
+ db._conn.execute(
+ "INSERT INTO messages (session_id, role, content, tool_call_id, tool_name, timestamp) "
+ "VALUES (?, 'tool', 'r2', 'call_x', 't', 6.0)", (sid,))
+ db._conn.commit()
+ db.append_message(session_id=sid, role="user", content="q3")
+ db.append_message(session_id=sid, role="assistant", content="", tool_calls=call)
+ db.append_message(session_id=sid, role="tool", content="r3", tool_call_id="call_x", tool_name="t")
+ db.append_message(session_id=sid, role="user", content="q4")
+ db.append_message(session_id=sid, role="tool", content="stray", tool_call_id="call_x", tool_name="t")
+
+ restored = db.get_messages_as_conversation(sid, repair_alternation=False)
+ by_content = {m["content"]: m for m in restored}
+ uid1 = by_content["r1"]["_tool_call_uid"]
+ uid3 = by_content["r3"]["_tool_call_uid"]
+ assert UID_RE.match(uid1) and UID_RE.match(uid3) and uid1 != uid3
+ assert "_tool_call_uid" not in by_content["r2"]
+ assert "_tool_call_uid" not in by_content["stray"]
+ # The same rule at batch insert: a result after a user turn pairs with nothing.
+ assert db._conn.execute(
+ "SELECT tool_call_uid FROM messages WHERE content = 'stray'").fetchone()[0] is None
+
+ def test_a_composite_rewind_reports_the_replacement_rows_uid(self, db):
+ from agent.context_compressor import HISTORICAL_TASK_HEADING, SUMMARY_PREFIX, _SUMMARY_END_MARKER
+
+ sid = "s"
+ db.create_session(sid, "cli", model="m")
+ db.append_message(session_id=sid, role="user", content="older ask")
+ db.append_message(session_id=sid, role="assistant", content="done")
+ carrier = f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n{_SUMMARY_END_MARKER}\n\nREAL ASK"
+ target_id = db.append_message(session_id=sid, role="user", content=carrier)
+ db.append_message(session_id=sid, role="assistant", content="failed")
+
+ result = db.rewind_to_message(sid, target_id, preserve_compaction_handoff=True,
+ expected_target_content="REAL ASK")
+
+ head = db.get_messages_as_conversation(sid, include_row_ids=True)[-1]
+ assert head["_row_id"] == result["replacement_message_id"]
+ assert result["replacement_message_uid"] == head["message_uid"]
+ assert UID_RE.match(head["message_uid"])
+
+ def test_a_live_undo_of_a_composite_turn_installs_the_replacement_rows_identity(self, db):
+ """The CLI/TUI/gateway undo path (``rewind_user_turn``) installs the hidden scaffold as the live head:
+ it must carry the replacement row's uid, not wait for a restart to learn it."""
+ from agent.context_compressor import HISTORICAL_TASK_HEADING, SUMMARY_PREFIX, _SUMMARY_END_MARKER
+
+ sid = "s"
+ db.create_session(sid, "cli", model="m")
+ db.append_message(session_id=sid, role="user", content="q1")
+ db.append_message(session_id=sid, role="assistant", content="a1")
+ carrier = f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n{_SUMMARY_END_MARKER}\n\nREAL ASK"
+ db.append_message(session_id=sid, role="user", content=carrier)
+ db.append_message(session_id=sid, role="assistant", content="failed")
+ warm = db.get_resume_conversations(sid)[0]
+
+ outcome = db.rewind_user_turn(sid, 1, warm_history=warm)
+
+ head = db.get_messages_as_conversation(sid, include_row_ids=True)[-1]
+ assert head["display_kind"] == "hidden" and SUMMARY_PREFIX in head["content"]
+ assert outcome.prefix[-1]["_row_id"] == head["_row_id"]
+ assert outcome.prefix[-1]["message_uid"] == head["message_uid"]
+ assert UID_RE.match(head["message_uid"])
+
+ def test_foreign_history_import_mints_uids_and_keeps_supplied_ones(self, db):
+ origin = {"tool": "other-agent", "path": "/x/y.jsonl"}
+ supplied = "f" * 32
+ result = db.import_foreign_history(
+ origin, [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello", "message_uid": supplied}],
+ title="imported", cwd="/tmp", profile="default")
+ rows = _rows(db, result["session_id"])
+ assert [r["content"] for r in rows] == ["hi", "hello"]
+ assert UID_RE.match(rows[0]["message_uid"]) and rows[1]["message_uid"] == supplied
+ assert [m["message_uid"] for m in db.get_messages_as_conversation(result["session_id"])] == [
+ rows[0]["message_uid"], supplied]
+
+ def test_a_restore_time_merge_records_the_witness(self, db):
+ """Two stored user rows in a row (a turn that never got an answer) are merged while restoring with
+ ``repair_alternation=True``; the survivor names the absorbed row by uid, on every restore shape."""
+ db.create_session("s", "cli", model="m")
+ db.append_message(session_id="s", role="user", content="first ask")
+ db.append_message(session_id="s", role="user", content="second ask")
+ db.append_message(session_id="s", role="assistant", content="answer")
+ first, second = [r["message_uid"] for r in _rows(db, "s")][:2]
+ for kwargs in ({}, {"include_row_ids": True}):
+ restored = db.get_messages_as_conversation("s", repair_alternation=True, **kwargs)
+ assert [m["role"] for m in restored] == ["user", "assistant"]
+ assert restored[0]["content"] == "first ask\n\nsecond ask"
+ assert restored[0]["message_uid"] == first
+ assert restored[0]["_absorbed_message_uids"] == [second]
+ assert db.get_resume_conversations("s")[0][0]["_absorbed_message_uids"] == [second]
+
def test_a_row_rewrite_keeps_the_tool_call_uids(self, db):
db.create_session("s", "cli")
assistant = {"role": "assistant", "content": "partial",
diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.md
index 1e9167fcc5e..bbd90b1aae8 100644
--- a/website/docs/developer-guide/context-engine-plugin.md
+++ b/website/docs/developer-guide/context-engine-plugin.md
@@ -160,16 +160,29 @@ 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 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.
+- **Merges keep the first constituent's uid and record the rest.** Whenever
+ the host folds one durable message into another (alternation repair's
+ consecutive-user and consecutive-assistant merges, the compressor restating
+ an in-flight task onto its summary carrier, the real user anchor folded into
+ a trailing scaffolding turn, micro-compaction's adjacent-user merge), the
+ composite keeps the uid of the constituent whose text comes first and
+ records the others in `_absorbed_message_uids` (text 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. Merges made while
+ restoring a history (`repair_alternation=True`) record the witness the same
+ way.
- **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.
+ output pre-stamps `message_uid` on a summary carrier (or any row it emits),
+ the host writes that value through the commit, both in place and on
+ rotation, and every later restore and copy returns it; rows without one are
+ minted at insert. An engine can therefore recognise its own rows by uid.
+- **A uid names one logical message, not one row.** Copies of a message share
+ it by design, and a host path that re-appends an edited or merged message
+ next to a still-active earlier row (a persist override on a restored list,
+ a merged survivor flushed as a new row) leaves two active rows with one uid.
+ Never assume per-row uniqueness in the active set; key your own state on
+ the uid and treat the later row as the current version.
- **Tool calls get per-occurrence ids too.** Provider tool-call ids repeat
(Hermes mints deterministic `call_<12hex>` ids for identical calls, and models
reuse ids), so an assistant message carries `_tool_call_uids`, a
@@ -189,8 +202,9 @@ What the host guarantees:
- **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.
+ an older schema backfill a uid onto every existing row once (schema v31),
+ and an insert trigger mints one for any row an older build writes into a
+ v31 store afterwards (that build's live dicts still lack it until restored).
### When to use these hooks — and when NOT to
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 0b7ce999d7a..261c6035af1 100644
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@ -244,7 +244,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.
+- `absorbed_message_uids` is the merge witness: a JSON list of the `message_uid`s the host folded into this row (alternation repair's user and assistant merges, the compressor's in-flight restatement and anchor folds, micro-compaction's adjacent-user merge; the composite keeps the first constituent's uid). Written when the survivor is flushed, rewritten with it, restored as the live `_absorbed_message_uids`, `NULL` on rows that absorbed nothing.
- `tool_call_uids` (assistant rows) is a JSON `{tool_call_id: uid}` map giving each entry of `tool_calls` a per-occurrence id, because provider tool-call ids repeat; `tool_call_uid` (tool rows) is the matching value for the result. The `tool_calls` JSON itself is never modified. Minted at the assistant row's first insert, paired onto the result at flush or, when the column is `NULL`, derived on restore from the preceding assistant row; restored as the live `_tool_call_uids` / `_tool_call_uid`.
### FTS5 Full-Text Search
@@ -292,7 +292,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`, `absorbed_message_uids`, `tool_call_uids`, `tool_call_uid` (declarative column adds) plus a one-time backfill of a fresh `message_uid` onto every row that predates the column, so a v31 store hands every row to consumers with an id (tool-call uids are minted when a row is next written; results are paired on restore) |
+| 31 | `messages.message_uid`, `absorbed_message_uids`, `tool_call_uids`, `tool_call_uid` (declarative column adds), a one-time backfill of a fresh `message_uid` onto every row that predates the column (gated by the `message_uid_backfill` meta marker), and the `messages_message_uid_insert` trigger that mints one for any row inserted without it (an older build writing into the store), so a v31 store hands every row to consumers with an id (tool-call uids are minted when a row is next written; results are paired on restore) |
Versions not listed above were declarative column additions handled by `_reconcile_columns()` (version bump only, no data migration).