The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(sessions): simplify-code pass over the identity helpers
kshitijk4poor2be9fa5f9dac
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 4441f632788..7a4d0f9ca2e 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -382,9 +382,8 @@ def _is_codex_interim(m: Dict) -> bool:def _merge_assistant_into(prev: Dict, msg: Dict) -> bool:- """Fold a consecutive assistant ``msg`` into ``prev`` (union tool_calls, concat text). Returns whether- ``msg``'s text lives on in ``prev``: multimodal (list) content is never joined, so a non-empty ``msg``- content beside a list (or a list beside non-empty text) is discarded and must earn no merge witness."""+ """Fold consecutive assistant *msg* into *prev* (union tool_calls, concat text). Returns whether *msg*'s+ text survives: multimodal (list) content is never joined."""from agent.context_compressor import _DB_PERSISTED_MARKERprev_calls = list(prev.get("tool_calls") or [])@@ -393,8 +392,8 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> bool:if 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] = merge_tool_call_uids(prev.get(TOOL_CALL_UIDS) or {}, msg[TOOL_CALL_UIDS])+ if extra := msg.get(TOOL_CALL_UIDS):+ prev[TOOL_CALL_UIDS] = merge_tool_call_uids(prev.get(TOOL_CALL_UIDS) or {}, extra)calls_changed = Trueelif prev_calls:prev["tool_calls"] = prev_calls@@ -459,15 +458,10 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> bool:return text_kept-def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *, folded: bool = True) -> None:- """Record durable ids a merge folded into *survivor* and then dropped from the list.-- 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.- """+def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *, folded: bool) -> None:+ """Retire *dropped*'s row ids onto *survivor*; record its uid as a merge witness only when *folded* (its+ text survives). An empty incoming turn still merges; stamping an empty list would change a message that+ absorbed nothing."""ids = []row_id = dropped.get("_row_id")if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0:@@ -626,7 +620,7 @@ def _merge_consecutive_users(messages: List[Dict]) -> Tuple[List[Dict], int]:# reproduces the persisted bytes (e.g. an empty incoming turn) keeps its stamp.if merged_content != prev_content or had_api_sidecar:prev.pop(_DB_PERSISTED_MARKER, None)- _remember_absorbed_row(prev, msg)+ _remember_absorbed_row(prev, msg, folded=True)repairs += 1continuemerged.append(msg)diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 8235e5108e2..74ef6786223 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -17,7 +17,7 @@ from typing import Any, Dict, List, Optionalfrom agent.codex_responses_adapter import _summarize_user_message_for_logfrom agent.fast_mode import begin_turn as begin_fast_mode_turn-from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message+from agent.message_metadata import append_message, without_persistence_fieldsfrom agent.message_sanitization import _repair_tool_call_arguments, _sanitize_surrogatesfrom agent.model_metadata import MINIMUM_CONTEXT_LENGTH, _estimate_tools_tokens_roughfrom agent.process_bootstrap import _install_safe_stdio@@ -1319,13 +1319,8 @@ def _apply_context_engine_selection(# 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 all(PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(m) for m in selected):- return selected- return [- m if PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(m)- else {k: v for k, v in m.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}- for m in selected- ]+ stripped = [without_persistence_fields(m) for m in selected]+ return selected if all(a is b for a, b in zip(stripped, selected)) else strippedlogger.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.pyindex e7a16936827..cc49ab1cd49 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -42,6 +42,23 @@ PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset() | REPAIR_BOOKKEEPING_FIELDS+def without_persistence_fields(msg: Mapping[str, Any]) -> Mapping[str, Any]:+ """*msg* itself when it carries no persistence-only field, else a shallow copy without them."""+ if PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(msg):+ return msg+ return {k: v for k, v in msg.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}+++def mint_uid() -> str:+ """A fresh durable id (message or tool-call occurrence): random, never derived from content."""+ return uuid4().hex+++def uid_list(value: Any) -> List[str]:+ """The unique non-empty string uids of a live list, in order; anything else is ``[]``."""+ return list(dict.fromkeys(u for u in (value if isinstance(value, list) else ()) if isinstance(u, str) and u))++def message_uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:"""The dict's ``message_uid`` when it is a non-empty string, else ``None`` (never coerced: an int or ablank would be a bug upstream of the write, not an identity)."""@@ -50,7 +67,7 @@ def message_uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:def stamp_message_uid(msg: MutableMapping[str, Any]) -> str:- """The dict's ``message_uid``, minting one (``uuid4().hex``) when it carries none.+ """The dict's ``message_uid``, minting one (``mint_uid``) when it carries none.Minted ONCE per logical message, at its first insert, and stamped on the caller's dict so every laterinsert of that dict (compaction generation, rotation handoff, replace) writes the same uid. Never@@ -58,14 +75,10 @@ def stamp_message_uid(msg: MutableMapping[str, Any]) -> str:"""uid = message_uid_or_none(msg)if uid is None:- uid = msg[MESSAGE_UID] = uuid4().hex+ uid = msg[MESSAGE_UID] = mint_uid()return uid-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]--_IDENTITY_FIELD_TYPES = ((MESSAGE_UID, str), (ABSORBED_MESSAGE_UIDS, list), (TOOL_CALL_UIDS, dict), (TOOL_CALL_UID, str))@@ -108,9 +121,11 @@ def record_absorbed_message(dropped_uid = message_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)+ ordered = uid_list(dropped.get(ABSORBED_MESSAGE_UIDS)) + ([survivor_uid] if survivor_uid else []) + uid_list(+ survivor.get(ABSORBED_MESSAGE_UIDS))else:- ordered = _absorbed_uids(survivor) + ([dropped_uid] if dropped_uid else []) + _absorbed_uids(dropped)+ ordered = uid_list(survivor.get(ABSORBED_MESSAGE_UIDS)) + ([dropped_uid] if dropped_uid else []) + uid_list(+ dropped.get(ABSORBED_MESSAGE_UIDS))absorbed: List[str] = []for uid in ordered:if uid != survivor.get(MESSAGE_UID) and uid not in absorbed:@@ -119,15 +134,6 @@ def record_absorbed_message(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 merge_tool_call_uids(into: Mapping[str, Any], extra: Mapping[str, Any]) -> dict:"""Union two ``_tool_call_uids`` maps without losing an occurrence. Folding two assistant turns thatreuse a provider id (llama.cpp-style constant ids) leaves both calls in ``tool_calls``; the id then maps@@ -142,29 +148,33 @@ def _uid_occurrences(value: Any) -> list:return list(value) if isinstance(value, list) else [value]-def index_tool_call_uids(index: MutableMapping[str, str], assistant: Any) -> None:+def index_tool_call_uids(index: MutableMapping[str, str], assistant: Mapping[str, Any]) -> frozenset:"""Register an assistant dict's ``_tool_call_uids`` under every pairing-id variant of its tool calls, so alater tool-result row can be resolved by any spelling of its ``tool_call_id``. Provider ids repeat, soevery id this assistant names first shadows an earlier occurrence's entry: a result pairs with theNEAREST preceding call, and a call without a uid (a legacy row) pairs its result with nothing. A- provider id repeated inside one row (two folded turns) maps each call to its own occurrence's uid."""+ provider id repeated inside one row (two folded turns) maps each call to its own occurrence's uid.+ Returns every pairing-id variant the assistant names."""from agent.message_sanitization import coalesce_tool_call_id, tool_call_id_variants- for variant in _named_tool_call_variants(assistant):+ calls = [(tc, tool_call_id_variants(tc)) for tc in assistant.get("tool_calls") or ()]+ named = frozenset(variant for _, variants in calls for variant in variants)+ for variant in named:index.pop(variant, None)- uids = assistant.get(TOOL_CALL_UIDS) if isinstance(assistant, dict) else None+ uids = assistant.get(TOOL_CALL_UIDS)if not isinstance(uids, dict) or not uids:- return+ return namedoccurrence: dict = {} # provider id -> calls seen so far: a list value holds one uid per occurrence- for tc in assistant.get("tool_calls") or ():+ for tc, variants in calls:call_id = coalesce_tool_call_id(tc)uid = uids.get(call_id)if isinstance(uid, list):nth = occurrence[call_id] = occurrence.get(call_id, -1) + 1uid = uid[nth] if nth < len(uid) else Noneif isinstance(uid, str) and uid:- for variant in tool_call_id_variants(tc):+ for variant in variants:index[variant] = uid+ return nameddef resolve_tool_call_uid(index: MutableMapping[str, str], tool_call_id: Any) -> Optional[str]:@@ -180,15 +190,12 @@ def resolve_tool_call_uid(index: MutableMapping[str, str], tool_call_id: Any) ->return None-def tool_call_uid_from_history(messages: Any, tool_index: int, owners: Optional[dict] = None) -> Optional[str]:+def tool_call_uid_from_history(messages: List[dict], tool_index: int, owners: dict) -> Optional[str]:"""Resolve a tool-result dict's uid from the nearest preceding assistant dict in ``messages`` thatnamed its ``tool_call_id`` (the cross-flush case: the assistant row landed in an earlier batch).``owners`` memoizes each assistant's (named variants, uid index) across one flush's results, so Kparallel results of one assistant cost O(K) variant work instead of O(K^2)."""- 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+ tool_call_id = messages[tool_index].get("tool_call_id")if not isinstance(tool_call_id, str) or not tool_call_id:return Nonefrom agent.message_sanitization import tool_result_id_variants@@ -202,13 +209,9 @@ def tool_call_uid_from_history(messages: Any, tool_index: int, owners: Optional[return None # a tool result never pairs across a user turnif prior.get("role") != "assistant":continue- entry = owners.get(id(prior)) if owners is not None else None- if entry is None:+ if (entry := owners.get(id(prior))) is None:index: dict = {}- index_tool_call_uids(index, prior)- entry = (frozenset(_named_tool_call_variants(prior)), index)- if owners is not None:- owners[id(prior)] = entry+ entry = owners[id(prior)] = (index_tool_call_uids(index, prior), index)named, index = entryif result_variants.isdisjoint(named):continuediff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex cf9bf2a78e8..e68aeb5cb2e 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -22,7 +22,7 @@ from agent import model_metadata_httpfrom utils import atomic_json_write, atomic_yaml_write, base_url_host_matches, base_url_hostnamefrom hermes_constants import OPENROUTER_MODELS_URL, openrouter_variant_base-from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS+from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, without_persistence_fieldslogger = logging.getLogger(__name__)@@ -2427,8 +2427,7 @@ def _estimate_message_tokens_cached(msg: Any, image_cost: int) -> int:# Persistence-only fields (identity, timestamps, display metadata) never reach the estimate: keep them# out of the key so stamping them neither costs a walk nor misses the memo.key = _msg_fingerprint(- {k: v for k, v in msg.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS} if type(msg) is dict else msg,- pins)+ without_persistence_fields(msg) if type(msg) is dict else msg, pins)hash(key)except Exception:text, images = _compute()diff --git a/agent/transcript_repair.py b/agent/transcript_repair.pyindex 485cefb8405..04b89f51e1e 100644--- a/agent/transcript_repair.py+++ b/agent/transcript_repair.py@@ -10,10 +10,9 @@ from typing import Any, Callable, Dict, List, Mappingfrom agent.context_compressor import _DB_PERSISTED_MARKERfrom agent.message_metadata import (- CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,- copy_identity_fields)+ CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, copy_identity_fields)from hermes_state_common import _id_chunks, _placeholders-from hermes_state_identity import _uid_map+from hermes_state_identity import _restore_row_identityfrom hermes_state_messages import _MESSAGE_WRITE_COLUMNS@@ -159,14 +158,7 @@ def resolve_and_repair_transcript_batch(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]- if stored_tool_uids := _uid_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"]+ _restore_row_identity(final_row, msg)msg[DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)if adopt:canonical = decode_row_fn(final_row)diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex 3bbf012dc1f..d66dd5ab648 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -13,6 +13,7 @@ from agent.reasoning_effort import (KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES, OPENAI_COMPAT_WIRE_EFFORTS, TOKENHUB_EFFORTS, clamp_effort,clamp_reasoning_config, kimi_supported_efforts, requested_effort,)+from agent.message_metadata import MESSAGE_UIDfrom agent.message_sanitization import normalize_finish_reason as _normalize_finish_reasonfrom agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_toolsfrom agent.prompt_builder import DEVELOPER_ROLE_MODELS@@ -35,7 +36,7 @@ _XAI_TOOL_SEARCH_ALIAS = "hermes_tool_search"# providers reject with HTTP 400 ("Extra inputs are not permitted")._STRIP_MSG_KEYS = ("codex_reasoning_items", "codex_message_items", "tool_name", "effect_disposition", "timestamp",- "platform_message_id", "api_content", "anthropic_content_blocks", "bedrock_content_blocks", "message_uid",+ "platform_message_id", "api_content", "anthropic_content_blocks", "bedrock_content_blocks", MESSAGE_UID,)_STRIP_TC_KEYS = ("call_id", "response_item_id")_HIGH_EFFORTS = {"high", "xhigh", "max", "ultra"}diff --git a/hermes_state_identity.py b/hermes_state_identity.pyindex 94055f283ea..0d6c8f82d71 100644--- a/hermes_state_identity.py+++ b/hermes_state_identity.py@@ -5,30 +5,26 @@from __future__ import annotationsimport json-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Mapping, MutableMapping, Optional-from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS+from agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS, uid_listfrom hermes_state_common import _json_or+def _live_or_column(msg: Mapping[str, Any], live_key: str, column: str) -> Any:+ """Flushed dicts and batch rows carry the live key; import payloads carry the column name."""+ return msg.get(live_key) if live_key in msg else msg.get(column)++def _uid_list(value: Any) -> List[str]:"""Normalize a uid list (a live list, or the JSON text an export/import carries) to unique non-emptystrings in order; anything else is ``[]``."""if isinstance(value, str):value = _json_or(value, [], "Failed to deserialize a message uid list, falling back to []")- if not isinstance(value, list):- return []- return list(dict.fromkeys(item for item in value if isinstance(item, str) and item))---def _uid_list_json(msg: Dict[str, Any], live_key: str, column: str) -> Optional[str]:- """JSON text for a uid-list column, read from the live key first (flushed dicts, batch rows) and the- column name second (import payloads); ``None`` when empty."""- uids = _uid_list(msg.get(live_key) if live_key in msg else msg.get(column))- return json.dumps(uids) if uids else None+ return uid_list(value)-def _uid_map(value: Any) -> Dict[str, str]:+def _uid_map(value: Any) -> Dict[str, Any]:"""Normalize a ``{tool call id: uid}`` map (a live dict, or the JSON text an export/import carries): anon-empty string uid, or a list of them for a provider id repeated inside one row (one per occurrence,see ``merge_tool_call_uids``); anything else is dropped, and a non-map is ``{}``."""@@ -40,23 +36,40 @@ def _uid_map(value: Any) -> Dict[str, str]:(isinstance(v, str) and v) or (isinstance(v, list) and v and all(isinstance(u, str) and u for u in v)))}-def _restore_identity_columns(row: Any, msg: Dict[str, Any]) -> None:- """The stored identity columns onto a restored dict under their live keys (NULL/empty add nothing)."""- if row[MESSAGE_UID]:- msg[MESSAGE_UID] = row[MESSAGE_UID]- if absorbed := _uid_list(row["absorbed_message_uids"]):- msg[ABSORBED_MESSAGE_UIDS] = absorbed- if 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"]+def _tool_call_uid_map(msg: Mapping[str, Any]) -> Dict[str, Any]:+ return _uid_map(_live_or_column(msg, TOOL_CALL_UIDS, "tool_call_uids"))+++def _absorbed_uids_json(msg: Mapping[str, Any]) -> Optional[str]:+ uids = _uid_list(_live_or_column(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"))+ return json.dumps(uids) if uids else None-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"))+def _tool_call_uids_json(msg: Mapping[str, Any]) -> Optional[str]:+ uids = _tool_call_uid_map(msg)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")+def _tool_call_uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:+ uid = _live_or_column(msg, TOOL_CALL_UID, "tool_call_uid")return uid if isinstance(uid, str) and uid else None+++def _restore_row_identity(row: Any, msg: MutableMapping[str, Any]) -> None:+ """A stored row's uid and tool-call uids onto its live dict: the stored value wins; pairings only the live+ dict knows (an un-persisted merge's union) stay."""+ if row[MESSAGE_UID]:+ msg[MESSAGE_UID] = row[MESSAGE_UID]+ if row["tool_call_uids"] and (stored := _uid_map(row["tool_call_uids"])):+ live = msg.get(TOOL_CALL_UIDS)+ live = live if isinstance(live, dict) else {}+ msg[TOOL_CALL_UIDS] = {**live, **stored}+ if row["tool_call_uid"]:+ msg[TOOL_CALL_UID] = row["tool_call_uid"]+++def _restore_identity_columns(row: Any, msg: MutableMapping[str, Any]) -> None:+ """The stored identity columns onto a restored dict under their live keys (NULL/empty add nothing)."""+ _restore_row_identity(row, msg)+ if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):+ msg[ABSORBED_MESSAGE_UIDS] = absorbeddiff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 6181e5c7893..7c137c04bc7 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -8,7 +8,6 @@ import jsonimport loggingimport reimport time-import uuidfrom typing import Any, Dict, List, Optional, Tuplefrom agent.context_compressor import (@@ -16,15 +15,15 @@ from agent.context_compressor import (_newest_checkpoint_carrier, split_user_originated_turn)from agent.memory_manager import sanitize_contextfrom agent.message_metadata import (- ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,- index_tool_call_uids, message_uid_or_none, resolve_tool_call_uid, stamp_message_uid)+ CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,+ index_tool_call_uids, message_uid_or_none, resolve_tool_call_uid, mint_uid, stamp_message_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,_json_or, _legacy_reset_child_sql, _placeholders, _sql_json_extract)from hermes_state_identity import (- _restore_identity_columns, _tool_call_uid_or_none, _tool_call_uids_json, _uid_list_json, _uid_map)+ _absorbed_uids_json, _restore_identity_columns, _tool_call_uid_map, _tool_call_uid_or_none, _tool_call_uids_json)logger = logging.getLogger("hermes_state") # caplog tests pin the origin module's name@@ -283,7 +282,7 @@ class SessionMessagesMixin:1 if msg.get("observed") else 0, 1 if msg.get("_compressed_summary") else 0, 1,_str_or_none(msg.get("api_content")), _str_or_none(msg.get("display_kind")),display_metadata, self._display_identity(self._display_dedupe_key(identity_row)),- message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"),+ message_uid_or_none(msg), _absorbed_uids_json(msg),_tool_call_uids_json(msg), _tool_call_uid_or_none(msg))@staticmethod@@ -295,11 +294,11 @@ class SessionMessagesMixin:(``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"))+ uids = _tool_call_uid_map(msg)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+ uids[call_id] = mint_uid()if uids:msg[TOOL_CALL_UIDS] = uidsindex_tool_call_uids(batch_index, msg) # this row's ids shadow any earlier occurrence's@@ -1810,7 +1809,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_message_uid = replacement = None+ replacement = Noneif 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",@@ -1818,22 +1817,21 @@ class SessionMessagesMixin:if ids:conn.execute(f"UPDATE messages SET active = 0 WHERE id IN ({_placeholders(ids)})", ids)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+ self._insert_message_rows(conn, session_id, [replacement]) # stamps _row_id and message_uidconn.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, replacement_message_uid- target_row, rewound, new_head_id, replacement_message_id, replacement_message_uid = self._execute_write(_do)+ return target_row, ids, head_id, replacement+ target_row, rewound, new_head_id, replacement = 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,- "replacement_message_uid": replacement_message_uid} if preserve_compaction_handoff else {})}+ **({"replacement_message_id": replacement and replacement["_row_id"],+ "replacement_message_uid": replacement and message_uid_or_none(replacement)}+ 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_schema.py b/hermes_state_schema.pyindex 6a78b4a6554..043688f0e0d 100644--- a/hermes_state_schema.py+++ b/hermes_state_schema.py@@ -28,6 +28,7 @@ from hermes_state_common import ()from hermes_state_fts import _drop_orphan_fts_shadow_tablesfrom hermes_state_holders import _read_proc_argv+from hermes_state_search import _delete_meta, _meta_rowfrom hermes_state_errors import is_sqlite_lock_error# Pre-split logger identity so log filtering/capture is unchanged.@@ -1116,11 +1117,9 @@ class SessionSchemaMixin:writer connection is autocommit) and an open spends at most ``_MESSAGE_UID_BACKFILL_BUDGET_S``after its first chunk, so a large store converges over later opens. Until then a legacy rowsimply has no uid, which every reader already treats as "no identity yet"."""- if cursor.execute(- "SELECT 1 FROM state_meta WHERE key = ? LIMIT 1", (_MESSAGE_UID_BACKFILL_DONE,)- ).fetchone() is not None:+ if _meta_row(cursor, _MESSAGE_UID_BACKFILL_DONE) is not None:return- row = cursor.execute("SELECT value FROM state_meta WHERE key = ?", (_MESSAGE_UID_BACKFILL_CURSOR,)).fetchone()+ row = _meta_row(cursor, _MESSAGE_UID_BACKFILL_CURSOR)done_through = int(row[0]) if row else 0high = cursor.execute("SELECT MAX(id) FROM messages").fetchone()[0] or 0deadline = time.monotonic() + _MESSAGE_UID_BACKFILL_BUDGET_S@@ -1134,7 +1133,7 @@ class SessionSchemaMixin:self.set_meta(_MESSAGE_UID_BACKFILL_CURSOR, str(done_through), cursor=cursor)returnself.set_meta(_MESSAGE_UID_BACKFILL_DONE, "1", cursor=cursor)- cursor.execute("DELETE FROM state_meta WHERE key = ?", (_MESSAGE_UID_BACKFILL_CURSOR,))+ _delete_meta(cursor, _MESSAGE_UID_BACKFILL_CURSOR)def _migrate_v22_session_model_usage(self, cursor: sqlite3.Cursor) -> None:"""v22: ``task`` joins the session_model_usage PRIMARY KEY ('' = main loop; aux callsdiff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.pyindex 78f47835901..0d781e96ef4 100644--- a/tests/agent/test_context_engine_message_uid.py+++ b/tests/agent/test_context_engine_message_uid.py@@ -262,11 +262,11 @@ def test_the_live_list_walk_binds_a_result_to_the_nearest_call_that_names_it():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+ 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+ 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+ assert tool_call_uid_from_history([call("1" * UID_LEN), {"role": "user", "content": "q"}, result], 2, {}) is Nonedef test_a_superseded_verification_candidate_is_not_a_witness_constituent():diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex 5b5cb6b2f2f..fc49ac08265 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -52,7 +52,6 @@ class TestMintAndRestore: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}) == 2def test_uid_is_per_occurrence_not_derived_from_content_or_time(self, db):db.create_session("s", "cli")@@ -72,12 +71,6 @@ class TestMintAndRestore: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_in_bounded_slices_across_opens(self, tmp_path, monkeypatch):"""A single full-table UPDATE held the write lock for minutes on a large store; each open nowmints at most one chunk past its time budget, keeps earlier uids, and converges."""@@ -471,3 +464,4 @@ def test_a_result_pairs_with_the_assistant_that_named_it_not_the_nearest_one(db)live = [{k: v for k, v in m.items() if k != "_tool_call_uid"} for m in msgs]owners: dict = {}assert [tool_call_uid_from_history(live, i, owners) for i in (3, 4)] == [second, first]+