The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(sessions): give tool calls and their results a per-occurrence uid
Eva76d0ac6caad9
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 0fcd6e46758..e9bd1eb8bec 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_timeoutfrom 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.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, TOOL_CALL_UIDSfrom agent.prompt_builder import STEER_DISPLAY_KIND, steer_user_rowfrom agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_messagefrom agent.think_scrubber import THINK_TAG_NAMES@@ -390,6 +390,9 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:calls_changed = Falseif new_calls:prev["tool_calls"] = prev_calls + new_calls+ # The absorbed turn's calls keep the per-occurrence ids they were persisted with.+ if isinstance(msg.get(TOOL_CALL_UIDS), dict) and msg[TOOL_CALL_UIDS]:+ prev[TOOL_CALL_UIDS] = {**(prev.get(TOOL_CALL_UIDS) or {}), **msg[TOOL_CALL_UIDS]}calls_changed = Trueelif prev_calls:prev["tool_calls"] = prev_callsdiff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex 68e31400262..f51cad36163 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -25,13 +25,70 @@ MERGED_TURN_PREFIX = "_merged_turn_prefix"# 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.+# The merge witness on a consecutive-user merge survivor: the ``message_uid`` of each absorbed row, in+# absorption order (the uid sibling of ``_absorbed_row_ids``; persisted as ``messages.absorbed_message_uids``).+# The survivor keeps the FIRST constituent's uid.ABSORBED_MESSAGE_UIDS = "_absorbed_message_uids"+# Per-occurrence tool-call identity. Provider tool-call ids repeat (Hermes mints deterministic ``call_<12hex>``+# ids for identical calls, and models reuse ids), so an assistant row carries ``{provider id: uid}`` for its+# ``tool_calls`` (``messages.tool_call_uids``) and its tool-result rows carry the matching uid+# (``messages.tool_call_uid``). The provider-facing ``id`` is untouched; these never reach the wire.+TOOL_CALL_UIDS = "_tool_call_uids"+TOOL_CALL_UID = "_tool_call_uid"PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(- {"timestamp", "display_kind", "display_metadata", "_row_id", MERGED_TURN_PREFIX, MESSAGE_UID, ABSORBED_MESSAGE_UIDS}+ {"timestamp", "display_kind", "display_metadata", "_row_id", MERGED_TURN_PREFIX, MESSAGE_UID,+ ABSORBED_MESSAGE_UIDS, TOOL_CALL_UIDS, TOOL_CALL_UID}) | REPAIR_BOOKKEEPING_FIELDS++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``."""+ from agent.message_sanitization import coalesce_tool_call_id, tool_call_id_variants++ uids = assistant.get(TOOL_CALL_UIDS) if isinstance(assistant, dict) else None+ if not isinstance(uids, dict) or not uids:+ return+ for tc in assistant.get("tool_calls") or ():+ uid = uids.get(coalesce_tool_call_id(tc))+ if isinstance(uid, str) and uid:+ for variant in tool_call_id_variants(tc):+ index[variant] = uid+++def resolve_tool_call_uid(index: MutableMapping[str, str], tool_call_id: Any) -> Optional[str]:+ """The uid an indexed assistant dict minted for ``tool_call_id`` (any variant), else ``None``."""+ from agent.message_sanitization import tool_result_id_variants++ if not index or not isinstance(tool_call_id, str) or not tool_call_id:+ return None+ for variant in tool_result_id_variants(tool_call_id):+ uid = index.get(variant)+ if uid:+ return uid+ return None+++def tool_call_uid_from_history(messages: Any, tool_index: int) -> Optional[str]:+ """Resolve a tool-result dict's uid from the nearest preceding assistant dict in ``messages`` that+ named its ``tool_call_id`` (the cross-flush case: the assistant row landed in an earlier batch)."""+ if not isinstance(messages, list) or not (0 <= tool_index < len(messages)):+ return None+ tool_msg = messages[tool_index]+ 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+ 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":+ return None # a tool result never pairs across a user turn+ return None+_Message = TypeVar("_Message", bound=MutableMapping[str, Any])diff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 562e031afd8..3bbcc4f6b28 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -23,7 +23,9 @@ from agent.memory_manager import sanitize_contextfrom agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summaryfrom agent.trajectory import save_trajectory as _save_trajectory_to_file-from agent.message_metadata import ABSORBED_MESSAGE_UIDS, DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS+from agent.message_metadata import (+ ABSORBED_MESSAGE_UIDS, DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS, TOOL_CALL_UID,+ TOOL_CALL_UIDS, tool_call_uid_from_history)from agent.transcript_repair import sync_flushed_message_markers@@ -242,6 +244,10 @@ def _db_flush_row(agent, msg: Dict, is_current_turn_user: bool) -> Dict[str, Any# The merge witness rides on the survivor's row (an owned column: a row-addressed rewrite of the# survivor writes it too), so a restart sees which rows the composite folded.row[ABSORBED_MESSAGE_UIDS] = list(msg[ABSORBED_MESSAGE_UIDS])+ if isinstance(msg.get(TOOL_CALL_UIDS), dict) and msg[TOOL_CALL_UIDS]:+ row[TOOL_CALL_UIDS] = dict(msg[TOOL_CALL_UIDS])+ if isinstance(msg.get(TOOL_CALL_UID), str) and msg[TOOL_CALL_UID]:+ row[TOOL_CALL_UID] = msg[TOOL_CALL_UID]if isinstance(msg.get(DB_ROW_SNAPSHOT), str):row[DB_ROW_SNAPSHOT] = msg[DB_ROW_SNAPSHOT]return row@@ -277,6 +283,11 @@ def _db_flush_collect(agent, messages: List[Dict], conversation_history: Optiona# context intact while transcript pollers omit unsolicited presentation.msg["display_kind"] = "hidden"msg["display_metadata"] = {**(msg.get("display_metadata") or {}), "notification_category": "diagnostic"}+ if msg.get("role") == "tool" and not msg.get(TOOL_CALL_UID):+ # A result whose call was flushed in an earlier batch: pair it with the uid that assistant row+ # minted (same-batch pairing happens inside the insert).+ if (tool_uid := tool_call_uid_from_history(messages, msg_idx)) is not None:+ msg[TOOL_CALL_UID] = tool_uidbatch_rows.append(_db_flush_row(agent, msg, ov_idx == msg_idx or msg is pending_cli_message))batch_msgs.append(msg)return batch_rows, batch_msgsdiff --git a/agent/transcript_repair.py b/agent/transcript_repair.pyindex 08c785035ed..3c7ffc48a15 100644--- a/agent/transcript_repair.py+++ b/agent/transcript_repair.py@@ -9,15 +9,30 @@ import sqlite3from typing import Any, Callable, Dict, List, Mappingfrom agent.context_compressor import _DB_PERSISTED_MARKER-from agent.message_metadata import ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID+from agent.message_metadata import (+ ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS)from hermes_state_common import _id_chunks, _placeholdersfrom hermes_state_messages import _MESSAGE_WRITE_COLUMNS+def _json_map(text: Any) -> Dict[str, str]:+ """A stored ``{tool call id: uid}`` JSON object as a dict of non-empty strings (``{}`` on bad input)."""+ import json++ try:+ value = json.loads(text) if isinstance(text, str) else None+ except (TypeError, ValueError):+ value = None+ if not isinstance(value, dict):+ return {}+ return {k: v for k, v in value.items() if isinstance(k, str) and k and isinstance(v, str) and v}++# 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.-_NON_PAYLOAD_COLUMNS = frozenset({"session_id", "role", "timestamp", "active", "display_identity", MESSAGE_UID})+_NON_PAYLOAD_COLUMNS = frozenset(+ {"session_id", "role", "timestamp", "active", "display_identity", MESSAGE_UID, "tool_call_uids", "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@@ -155,6 +170,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 final_row["tool_call_uid"]:+ msg[TOOL_CALL_UID] = final_row["tool_call_uid"]msg[DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)if adopt:canonical = decode_row_fn(final_row)@@ -280,6 +299,10 @@ def sync_flushed_message_markers(batch_msgs: List[Dict[str, Any]], batch_rows: Lwritten[MESSAGE_UID] = row[MESSAGE_UID]if isinstance(row.get(ABSORBED_MESSAGE_UIDS), list) and row[ABSORBED_MESSAGE_UIDS]:written[ABSORBED_MESSAGE_UIDS] = list(row[ABSORBED_MESSAGE_UIDS])+ if isinstance(row.get(TOOL_CALL_UIDS), dict) and row[TOOL_CALL_UIDS]:+ written[TOOL_CALL_UIDS] = dict(row[TOOL_CALL_UIDS])+ if isinstance(row.get(TOOL_CALL_UID), str) and row[TOOL_CALL_UID]:+ written[TOOL_CALL_UID] = row[TOOL_CALL_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.pyindex 83acb04bd83..dca255c379c 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1611,7 +1611,7 @@ class SessionDB("finish_reason, reasoning, reasoning_content, reasoning_details, ""codex_reasoning_items, codex_message_items, platform_message_id, observed, ""_compressed_summary, timestamp, active, api_content, display_kind, display_metadata, message_uid, "- "absorbed_message_uids"+ "absorbed_message_uids, tool_call_uids, tool_call_uid")# ── Meta key/value (scheduler bookkeeping) ──diff --git a/hermes_state_common.py b/hermes_state_common.pyindex ab8363f3c00..5419a5148cb 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -453,7 +453,9 @@ CREATE TABLE IF NOT EXISTS messages (display_identity BLOB,display_order INTEGER,message_uid TEXT,- absorbed_message_uids TEXT+ absorbed_message_uids TEXT,+ tool_call_uids TEXT,+ tool_call_uid TEXT);CREATE TABLE IF NOT EXISTS session_model_usage (diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 553d7e91b7c..afbe64b86fd 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -15,8 +15,10 @@ 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 ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID-from agent.message_sanitization import _sanitize_surrogates+from agent.message_metadata import (+ ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,+ index_tool_call_uids, resolve_tool_call_uid)+from agent.message_sanitization import _sanitize_surrogates, coalesce_tool_call_idfrom hermes_cli.timefmt import coerce_epochfrom hermes_state_common import (_COMPRESSION_LOCK_ROW_SQL, _ENDED_ROW_SQL, _RESET_END_REASONS, _RESET_END_REASONS_SQL, _ended_by_compression,@@ -29,8 +31,9 @@ _INSERT_MESSAGE_SQL = """INSERT INTO messages (session_id, role, content, tool_ctool_calls, tool_name, effect_disposition, timestamp, token_count, finish_reason,reasoning, reasoning_content, reasoning_details, codex_reasoning_items,codex_message_items, platform_message_id, observed, _compressed_summary, active, api_content, display_kind,- display_metadata, display_identity, message_uid, absorbed_message_uids)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""+ display_metadata, display_identity, message_uid, absorbed_message_uids, tool_call_uids,+ tool_call_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"].@@ -115,6 +118,26 @@ def _uid_list_json(msg: Dict[str, Any], live_key: str, column: str) -> Optional[return json.dumps(uids) if uids else None+def _uid_map(value: Any) -> Dict[str, str]:+ """Normalize a ``{tool call id: uid}`` map (a live dict, or the JSON text an export/import carries) to+ non-empty string pairs; anything else is ``{}``."""+ if isinstance(value, str):+ value = _json_or(value, {}, "Failed to deserialize a tool-call uid map, falling back to {}")+ if not isinstance(value, dict):+ return {}+ return {k: v for k, v in value.items() if isinstance(k, str) and k and isinstance(v, str) and v}+++def _tool_call_uids_json(msg: Dict[str, Any]) -> Optional[str]:+ uids = _uid_map(msg.get(TOOL_CALL_UIDS) if TOOL_CALL_UIDS in msg else msg.get("tool_call_uids"))+ return json.dumps(uids, sort_keys=True) if uids else None+++def _tool_call_uid_or_none(msg: Dict[str, Any]) -> Optional[str]:+ uid = msg.get(TOOL_CALL_UID) if TOOL_CALL_UID in msg else msg.get("tool_call_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):@@ -311,7 +334,30 @@ class SessionMessagesMixin:1 if msg.get("observed") else 0, 1 if msg.get("_compressed_summary") else 0, 1,_str_or_none(msg.get("api_content")), _str_or_none(msg.get("display_kind")),display_metadata, self._display_identity(self._display_dedupe_key(identity_row)),- _message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"))+ _message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"),+ _tool_call_uids_json(msg), _tool_call_uid_or_none(msg))++ @staticmethod+ def _stamp_tool_call_uids(msg: Dict[str, Any], tool_calls: Any, batch_index: Dict[str, str]) -> None:+ """Per-occurrence tool-call identity at insert: an assistant row gets a uid for every tool call that+ has none yet (``_tool_call_uids``, keyed by the effective provider id, which stays untouched); a+ tool-result row that has none is resolved through *batch_index*, the calls the same batch's+ assistant rows named. A result flushed in a later batch is resolved from the live list by the flush+ (``tool_call_uid_from_history``) or, on restore, from the preceding assistant row."""+ role = msg.get("role")+ if role == "assistant" and tool_calls:+ uids = _uid_map(msg.get(TOOL_CALL_UIDS) if TOOL_CALL_UIDS in msg else msg.get("tool_call_uids"))+ for tc in tool_calls:+ call_id = coalesce_tool_call_id(tc)+ if call_id and call_id not in uids:+ uids[call_id] = uuid.uuid4().hex+ if uids:+ msg[TOOL_CALL_UIDS] = uids+ index_tool_call_uids(batch_index, msg)+ 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:+ msg[TOOL_CALL_UID] = uid@staticmethoddef _stamp_message_uid(msg: Dict[str, Any]) -> str:@@ -366,6 +412,10 @@ class SessionMessagesMixin:msg[MESSAGE_UID] = row[MESSAGE_UID]if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):msg[ABSORBED_MESSAGE_UIDS] = absorbed+ if row["tool_call_uids"] and (tool_uids := _uid_map(row["tool_call_uids"])):+ msg[TOOL_CALL_UIDS] = tool_uids+ if row["tool_call_uid"]:+ msg[TOOL_CALL_UID] = row["tool_call_uid"]if row["api_content"] is not None:msg["api_content"] = row["api_content"]if row["display_kind"] is not None:@@ -416,6 +466,7 @@ class SessionMessagesMixin: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+ self._stamp_tool_call_uids(msg, tool_calls, {})params = self._message_row_params(session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=True)def _do(conn):@@ -732,14 +783,16 @@ class SessionMessagesMixin:are archived again (:meth:`_prune_shadowed_checkpoints`)."""now_ts = time.time()inserted = tool_calls_total = 0+ batch_tool_index: Dict[str, str] = {}for msg in messages: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.+ # the live dict never disagree. Tool calls get their per-occurrence ids the same way.self._stamp_message_uid(msg)+ self._stamp_tool_call_uids(msg, tool_calls, batch_tool_index)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@@ -1569,6 +1622,7 @@ class SessionMessagesMixin:from hermes_state import _strip_background_review_harness, _strip_stale_tool_call_markersmessages = []exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {}+ tool_uid_index: Dict[str, str] = {} # pairing-id variant -> uid, from the assistant rows read so farfor row in rows:content = self._loaded_view_content(row["role"], self._decode_content(row["content"]))# Underscore-prefixed like ``_row_id``: transports strip it before the wire; compression's@@ -1609,6 +1663,15 @@ class SessionMessagesMixin:msg.update((col, _json_or(row[col], None, f"Failed to deserialize {col}, falling back to None"))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+ index_tool_call_uids(tool_uid_index, msg)+ 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.+ tool_uid = row["tool_call_uid"] or resolve_tool_call_uid(tool_uid_index, row["tool_call_id"])+ if tool_uid:+ msg[TOOL_CALL_UID] = tool_uidif include_ancestors:skip, exact_clone_key = self._dedupe_replayed_user(messages, msg, exact_user_clones)if skip:diff --git a/hermes_state_portability.py b/hermes_state_portability.pyindex c8608781719..304cedc7ec0 100644--- a/hermes_state_portability.py+++ b/hermes_state_portability.py@@ -31,7 +31,7 @@ _IMPORT_MESSAGE_TEXT_FIELDS = ("reasoning", "reasoning_content", "platform_message_id", "message_id",)_IMPORT_MESSAGE_JSON_FIELDS = (- "reasoning_details", "codex_reasoning_items", "codex_message_items", "absorbed_message_uids",+ "reasoning_details", "codex_reasoning_items", "codex_message_items", "absorbed_message_uids", "tool_call_uids",)_IMPORT_SESSION_INSERT_SQL = """INSERT INTO sessions (id, source, user_id, model, model_config, system_prompt,diff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.pyindex 1bec373ab71..fd420d2a264 100644--- a/tests/agent/test_context_engine_message_uid.py+++ b/tests/agent/test_context_engine_message_uid.py@@ -214,7 +214,42 @@ def test_restart_after_a_merge_still_sees_the_composites_constituents(db):assert prompt["message_uid"] in survivor["_absorbed_message_uids"]+def test_tool_result_flushed_after_its_call_pairs_through_the_live_list(db):+ """Tool round shape: the assistant(tool_calls) row is flushed first, the result in a later flush."""+ sid = "20260928_120400_tool"+ db.create_session(sid, "cli", model="test/model")+ agent = _make_agent(db, sid)+ agent._session_db_created = True+ assistant = {"role": "assistant", "content": "",+ "tool_calls": [{"id": "call_x", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}+ messages = [{"role": "user", "content": "q"}, assistant]+ agent._persist_user_message_idx = 0+ agent._persist_session(messages, conversation_history=None)+ uid = assistant["_tool_call_uids"]["call_x"]+ result = {"role": "tool", "content": "r", "tool_call_id": "call_x", "tool_name": "t"}+ messages.append(result)+ agent._persist_session(messages, conversation_history=None)+ assert result["_tool_call_uid"] == uid+ stored = db._conn.execute(+ "SELECT tool_call_uid FROM messages WHERE session_id = ? AND role = 'tool'", (sid,)).fetchone()[0]+ assert stored == uid+++def test_assistant_merge_keeps_the_absorbed_turns_tool_call_uids():+ from agent.agent_runtime_helpers import _merge_consecutive_assistants++ first = {"role": "assistant", "content": "a",+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}],+ "_tool_call_uids": {"call_1": "1" * UID_LEN}}+ second = {"role": "assistant", "content": "b",+ "tool_calls": [{"id": "call_2", "type": "function", "function": {"name": "t", "arguments": "{}"}}],+ "_tool_call_uids": {"call_2": "2" * UID_LEN}}+ merged, repairs = _merge_consecutive_assistants([first, second])+ assert repairs == 1 and merged == [first]+ assert first["_tool_call_uids"] == {"call_1": "1" * UID_LEN, "call_2": "2" * UID_LEN}++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+ assert {"message_uid", "_absorbed_message_uids", "_tool_call_uids", "_tool_call_uid"} <= PERSISTENCE_ONLY_MESSAGE_FIELDSdiff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex c8a53a4a85f..cbbd3377875 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -243,6 +243,68 @@ class TestPersistedMergeWitness:assert _absorbed(db, "s") == ['["%s", "%s"]' % ("b" * 32, "c" * 32)]assert db.get_messages_as_conversation("s")[0]["_absorbed_message_uids"] == ["b" * 32, "c" * 32]+ def test_tool_call_uids_are_minted_on_the_assistant_and_paired_onto_the_results(self, db):+ db.create_session("s", "cli")+ calls = [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}},+ {"id": "call_2", "type": "function", "function": {"name": "t", "arguments": "{}"}}]+ assistant = {"role": "assistant", "content": "", "tool_calls": calls}+ first = {"role": "tool", "content": "r1", "tool_call_id": "call_1", "tool_name": "t"}+ db.append_messages_batch("s", [assistant, first])+ uids = assistant["_tool_call_uids"]+ assert set(uids) == {"call_1", "call_2"} and len({*uids.values()}) == 2+ assert all(UID_RE.match(u) for u in uids.values())+ assert first["_tool_call_uid"] == uids["call_1"]+ # The provider-facing entries are untouched: the stored tool_calls JSON carries no uid.+ stored_calls = db._conn.execute(+ "SELECT tool_calls FROM messages WHERE session_id = ? AND role = 'assistant'", ("s",)).fetchone()[0]+ assert "uid" not in stored_calls and [c["id"] for c in calls] == ["call_1", "call_2"]+ # A result that lands in a LATER batch with no live list to pair it: stored NULL, derived on restore+ # from the assistant row that named it (rows are read in id order).+ second = {"role": "tool", "content": "r2", "tool_call_id": "call_2", "tool_name": "t"}+ db.append_messages_batch("s", [second])+ assert "_tool_call_uid" not in second+ restored = db.get_messages_as_conversation("s")+ assert restored[0]["_tool_call_uids"] == uids+ assert [m["_tool_call_uid"] for m in restored[1:]] == [uids["call_1"], uids["call_2"]]++ def test_tool_call_uids_survive_compaction_copies_rotation_and_import(self, db, tmp_path):+ db.create_session("s", "cli")+ assistant = {"role": "assistant", "content": "",+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}+ result = {"role": "tool", "content": "r", "tool_call_id": "call_1", "tool_name": "t"}+ db.append_messages_batch("s", [{"role": "user", "content": "q"}, assistant, result,+ {"role": "assistant", "content": "done"}])+ uid = assistant["_tool_call_uids"]["call_1"]+ restored = db.get_messages_as_conversation("s")+ db.archive_and_compact("s", [{"role": "user", "content": "[CONTEXT COMPACTION] s"},+ copy.copy(restored[1]), copy.copy(restored[2]), copy.copy(restored[3])])+ after = db.get_messages_as_conversation("s")+ assert after[1]["_tool_call_uids"] == {"call_1": uid} and after[2]["_tool_call_uid"] == uid+ db.publish_compression_child(+ parent_session_id="s", child_session_id="child", source="cli",+ messages=[copy.copy(m) for m in after], require_compression_lease=False)+ child = db.get_messages_as_conversation("child")+ assert child[1]["_tool_call_uids"] == {"call_1": uid} and child[2]["_tool_call_uid"] == uid+ other = SessionDB(db_path=tmp_path / "other.db")+ try:+ assert other.import_sessions([db.export_session("child")])["ok"]+ imported = other.get_messages_as_conversation("child")+ assert imported[1]["_tool_call_uids"] == {"call_1": uid} and imported[2]["_tool_call_uid"] == uid+ finally:+ other.close()++ def test_a_row_rewrite_keeps_the_tool_call_uids(self, db):+ db.create_session("s", "cli")+ assistant = {"role": "assistant", "content": "partial",+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}+ db.append_messages_batch("s", [assistant])+ uids = dict(assistant["_tool_call_uids"])+ assistant["content"] = "partial, then filled by the sanitizer"+ db.append_messages_batch("s", [assistant])+ rows = _rows(db, "s")+ assert len(rows) == 1 and rows[0]["content"] == "partial, then filled by the sanitizer"+ assert db.get_messages_as_conversation("s")[0]["_tool_call_uids"] == uids+def test_compaction_copy_and_export_import_keep_the_witness(self, db, tmp_path):db.create_session("s", "cli")composite = {"role": "user", "content": "a\n\nb", "message_uid": "a" * 32,diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.mdindex 52a2c31e063..1e9167fcc5e 100644--- a/website/docs/developer-guide/context-engine-plugin.md+++ b/website/docs/developer-guide/context-engine-plugin.md@@ -170,7 +170,19 @@ What the host guarantees:- **Engine-authored rows keep the uid the engine sets.** If your `compress()`output pre-stamps `message_uid` on a summary carrier, the host writes thatvalue; rows without one are minted at insert.-- **Never on the wire.** `message_uid` and `_absorbed_message_uids` are in+- **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+ `{tool_call_id: uid}` map for its `tool_calls`, and each tool-result message+ carries the matching `_tool_call_uid`. The provider-facing `id` inside+ `tool_calls` is untouched. Both are minted at the assistant row's first+ insert, paired onto the result when it is flushed (same batch, or from the+ live list when the result lands in a later flush) and on restore (from the+ preceding assistant row), persisted (`messages.tool_call_uids`,+ `messages.tool_call_uid`), and kept across the same copy and rewrite paths+ as `message_uid`. A result whose call was never persisted with a uid has none.+- **Never on the wire.** `message_uid`, `_absorbed_message_uids`,+ `_tool_call_uids` and `_tool_call_uid` are in`PERSISTENCE_ONLY_MESSAGE_FIELDS`: stripped from every outgoing providercopy and ignored by the token estimator. Engines that never read them areunaffected.diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex 992ba5d4de9..0b7ce999d7a 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -207,7 +207,8 @@ later.Abridged — the full schema also includes `effect_disposition`,`platform_message_id`, `observed`, `active`, `compacted`, `api_content`,-`display_kind`, `display_metadata`, `message_uid`, and `absorbed_message_uids`:+`display_kind`, `display_metadata`, `message_uid`, `absorbed_message_uids`,+`tool_call_uids`, and `tool_call_uid`:```sqlCREATE TABLE IF NOT EXISTS messages (@@ -244,6 +245,7 @@ Notes:- 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.+- `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@@ -290,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` (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 |+| 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) |Versions not listed above were declarative column additions handled by `_reconcile_columns()` (version bump only, no data migration).