The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): branch and seed copies write the identity their live history keeps
kshitijk4poorc9a1c0793a12
diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex 6ce0071867f..212b13d2cea 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -78,6 +78,16 @@ def copy_identity_fields(src: Mapping[str, Any], dst: MutableMapping[str, Any])dst[key] = kind(value) if kind is not str else value+def message_identity(msg: MutableMapping[str, Any]) -> dict:+ """The identity fields a new row copied from *msg* must carry, minting *msg*'s uid first when it has none:+ a branch/seed copy writes fresh rows from the live dicts the new session keeps using, and a row without+ them would restore with a different uid than the live dict carries."""+ stamp_message_uid(msg)+ identity: dict = {}+ copy_identity_fields(msg, identity)+ return identity++def record_absorbed_message(survivor: MutableMapping[str, Any], dropped: Mapping[str, Any], *, dropped_leads: bool = False,) -> None:diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex be979df8dd5..f884ba755f2 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -30,6 +30,7 @@ from rich.panel import Panelfrom hermes_constants import display_hermes_homefrom hermes_state_ids import new_session_id as mint_session_idfrom agent.i18n import t+from agent.message_metadata import message_identityfrom agent.turn_context import extract_api_content_sidecarfrom hermes_cli.cli_agent_setup_mixin import _retire_agentfrom hermes_cli.browser_connect import (@@ -1420,7 +1421,7 @@ class CLICommandsMixin:self._session_db.append_messages_batch(new_session_id, [{"role": msg.get("role", "user"), "tool_name": msg.get("tool_name") or msg.get("name"),"api_content": extract_api_content_sidecar(msg),- **{k: msg.get(k) for k in _BRANCH_COPY_KEYS}}+ **{k: msg.get(k) for k in _BRANCH_COPY_KEYS}, **message_identity(msg)}for msg in self.conversation_history], chunk_rows=500)with suppress(Exception):self._session_db.set_session_title(new_session_id, branch_title)diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex 3a870c44b77..76f36402751 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -441,3 +441,20 @@ class TestPersistedMergeWitness:assert other.get_messages_as_conversation("s")[1]["_absorbed_message_uids"] == ["b" * 32]finally:other.close()+++def test_a_branch_copy_writes_the_uids_its_live_history_keeps(tmp_path):+ """The branch child keeps using the copied live dicts; rows minted with other uids would restore a+ different identity than the running agent saw. A dict without a uid gets one on both sides."""+ from tui_gateway import server++ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ db.create_session("parent", source="desktop", model="m")+ history = [{"role": "user", "content": "hello", "message_uid": "a" * 32}, {"role": "assistant", "content": "hi"}]+ server._persist_branch(db, "child", "parent", "Branch", history, source="desktop", cwd=str(tmp_path),+ profile_name="default", model="m")+ assert [r["message_uid"] for r in _rows(db, "child")] == [m.get("message_uid") for m in history]+ assert history[0]["message_uid"] == "a" * 32 and UID_RE.match(history[1]["message_uid"])+ finally:+ db.close()diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 2e2db54971d..dbab908e4da 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -242,6 +242,8 @@ def _persist_branch(db, new_key: str, parent_key: str, title: str, history: listdeletes a committed row whose transcript/title failed (a durable-but-empty row would defeat the INSERT ORIGNORE first-prompt seed) — except on disk-full, where the delete cannot land. ``user_id`` is the creatinglogin: the child is a Desktop session too, and the row only records identity at insert."""+ from agent.message_metadata import message_identity+# The child sends the parent's exact system prompt: a row without one makes the branch's first# turn rebuild (re-probing the workspace) and forfeits the warm cache the copied transcript buys.parent_prompt = None@@ -262,7 +264,8 @@ def _persist_branch(db, new_key: str, parent_key: str, title: str, history: list# rows, and per-row transactions were the write-amplification pattern removed in #23254.db.append_messages_batch(new_key, [{"role": msg.get("role", "user"), "content": msg.get("content"),- **{field: msg.get(field) for field in copy_fields}} for msg in history], chunk_rows=500)+ **{field: msg.get(field) for field in copy_fields}, **message_identity(msg)}+ for msg in history], chunk_rows=500)if title_source == "user":db.set_session_title(new_key, title)else:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 9080ee5bfd3..472fab9c9e9 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -453,8 +453,9 @@ def _persist_branch_seed(session: dict) -> None:``history`` and must never re-append it."""if not (key := session.get("session_key")) or not session.get("seeded") or session.get("_branch_seed_persisted"):return+ from agent.message_metadata import message_identitywith session["history_lock"]:- seed = [dict(msg) for msg in (session.get("history") or [])]+ seed = [{**msg, **message_identity(msg)} for msg in (session.get("history") or [])]if not seed:returnwith _session_db(session) as db:@@ -466,7 +467,8 @@ def _persist_branch_seed(session: dict) -> None:# Bounded-chunk transactions (see #23254): a branch seed can be hundreds of rows; chunking keeps# each BEGIN IMMEDIATE short so concurrent writers aren't starved.db.append_messages_batch(- key, [{"role": msg.get("role", "user"), **{f: msg.get(f) for f in _WORKDIR_SEED_FIELDS}} for msg in seed],+ key, [{"role": msg.get("role", "user"), **{f: msg.get(f) for f in _WORKDIR_SEED_FIELDS},+ **message_identity(msg)} for msg in seed],chunk_rows=500)session["_branch_seed_persisted"] = Trueexcept Exception as exc: