Skip to content

The agent that grows with you

fix(state,cli,tui-gateway): keep reasoning fields intact across forks and branches

cryptoyasenkaf2d03c1f2aac
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index 889fb02a4c9..3ad6e451b54 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -1263,6 +1263,9 @@ class CLICommandsMixin:
"tool_calls": msg.get("tool_calls"),
"tool_call_id": msg.get("tool_call_id"),
"reasoning": msg.get("reasoning"),
+ "reasoning_details": msg.get("reasoning_details"),
+ "codex_reasoning_items": msg.get("codex_reasoning_items"),
+ "codex_message_items": msg.get("codex_message_items"),
# Keep the api_content sidecar so the branch's first turn
# replays the parent's exact wire bytes (warm provider
# prompt cache) instead of a full cold prefill.
diff --git a/hermes_state.py b/hermes_state.py
index 24e840c0364..c510ff41d19 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -7014,6 +7014,28 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return None
return meta
+ @staticmethod
+ def _reasoning_json_text(value: Any) -> Optional[str]:
+ """Serialize a structured reasoning field for its TEXT column.
+
+ ``reasoning_details`` / ``codex_reasoning_items`` / ``codex_message_items``
+ arrive as list/dict structures from the live runtime, but callers that
+ round-trip stored rows — ``get_messages`` straight into
+ ``replace_messages``, e.g. the POST /api/sessions/{id}/fork handler —
+ hand back the raw TEXT these columns already hold, because
+ ``get_messages`` only deserializes ``content`` and ``tool_calls``.
+ Re-dumping that TEXT double-encodes it, and the forked session's next
+ ``get_messages_as_conversation`` json.loads then yields the inner
+ string instead of the original list, so every reasoning-replay consumer
+ (all of which check ``isinstance(..., list)``) silently drops it.
+ Strings are therefore stored as-is; structures are dumped.
+ """
+ if not value:
+ return None
+ if isinstance(value, str):
+ return value
+ return json.dumps(value)
+
def append_message(
self,
session_id: str,
@@ -7062,18 +7084,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# context role/content replayed to providers.
display_metadata_json = self._encode_display_metadata(display_metadata)
# Serialize structured fields to JSON before entering the write txn
- reasoning_details_json = (
- json.dumps(reasoning_details)
- if reasoning_details else None
- )
- codex_items_json = (
- json.dumps(codex_reasoning_items)
- if codex_reasoning_items else None
- )
- codex_message_items_json = (
- json.dumps(codex_message_items)
- if codex_message_items else None
- )
+ reasoning_details_json = self._reasoning_json_text(reasoning_details)
+ codex_items_json = self._reasoning_json_text(codex_reasoning_items)
+ codex_message_items_json = self._reasoning_json_text(codex_message_items)
# tool_calls may arrive as a Python list (from the live agent) or
# as a JSON string (from import/export). Parse first to avoid
# double-encoding.
@@ -7508,15 +7521,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
codex_message_items = (
msg.get("codex_message_items") if role == "assistant" else None
)
- reasoning_details_json = (
- json.dumps(reasoning_details) if reasoning_details else None
- )
- codex_items_json = (
- json.dumps(codex_reasoning_items) if codex_reasoning_items else None
- )
- codex_message_items_json = (
- json.dumps(codex_message_items) if codex_message_items else None
- )
+ reasoning_details_json = self._reasoning_json_text(reasoning_details)
+ codex_items_json = self._reasoning_json_text(codex_reasoning_items)
+ codex_message_items_json = self._reasoning_json_text(codex_message_items)
# tool_calls may arrive as a Python list (from the live agent)
# or as a JSON string (from import_sessions / export_session,
# which store it as TEXT). json.dumps on an already-serialized
diff --git a/tests/cli/test_branch_command.py b/tests/cli/test_branch_command.py
index 5927caefadb..ad1025d9076 100644
--- a/tests/cli/test_branch_command.py
+++ b/tests/cli/test_branch_command.py
@@ -6,6 +6,7 @@ Verifies that:
- Auto-generated titles use lineage numbering
- Custom branch names are used when provided
- parent_session_id links are set correctly
+- Structured reasoning fields survive the copy
- Edge cases: empty conversation, missing session DB
"""
@@ -181,3 +182,53 @@ class TestBranchFlushesBeforeEndSession:
cli_instance.conversation_history,
conversation_history=cli_instance.conversation_history,
)
+
+
+REASONING_DETAILS = [
+ {"type": "reasoning.text", "text": "sort in place instead", "format": "unknown"}
+]
+CODEX_REASONING_ITEMS = [
+ {"id": "rs_1", "type": "reasoning", "encrypted_content": "opaque-blob"}
+]
+CODEX_MESSAGE_ITEMS = [
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "done"}],
+ }
+]
+
+
+class TestBranchPreservesReasoningFields:
+ """The copy loop must carry the structured reasoning columns across.
+
+ Only ``reasoning`` was forwarded to append_message, so a branch dropped
+ the preserved Anthropic thinking blocks and the Codex
+ encrypted-reasoning/message-item continuation state that the parent had
+ accumulated — the branch then replayed without them, because every
+ consumer gates on isinstance(..., list) and a missing field reads as None.
+ """
+
+ def test_reasoning_fields_survive_branch(self, cli_instance, session_db):
+ from cli import HermesCLI
+
+ cli_instance.conversation_history = [
+ {"role": "user", "content": "Sort this list."},
+ {
+ "role": "assistant",
+ "content": "def sort_list(lst): return sorted(lst)",
+ "reasoning": "picked sorted()",
+ "reasoning_details": REASONING_DETAILS,
+ "codex_reasoning_items": CODEX_REASONING_ITEMS,
+ "codex_message_items": CODEX_MESSAGE_ITEMS,
+ },
+ ]
+
+ HermesCLI._handle_branch_command(cli_instance, "/branch")
+
+ messages = session_db.get_messages_as_conversation(cli_instance.session_id)
+ assistant = next(m for m in messages if m["role"] == "assistant")
+ assert assistant["reasoning_details"] == REASONING_DETAILS
+ assert assistant["codex_reasoning_items"] == CODEX_REASONING_ITEMS
+ assert assistant["codex_message_items"] == CODEX_MESSAGE_ITEMS
diff --git a/tests/hermes_state/test_reasoning_roundtrip.py b/tests/hermes_state/test_reasoning_roundtrip.py
new file mode 100644
index 00000000000..4fee37db2ac
--- /dev/null
+++ b/tests/hermes_state/test_reasoning_roundtrip.py
@@ -0,0 +1,118 @@
+"""Round-trip tests for the structured reasoning columns.
+
+get_messages() returns reasoning_details / codex_reasoning_items /
+codex_message_items as the raw TEXT stored in their columns (it only
+hydrates content and tool_calls). Callers that feed those rows straight
+back into a write — the POST /api/sessions/{id}/fork handler pipes
+get_messages() into replace_messages() — must not re-encode that TEXT,
+or the forked session replays with reasoning fields decoding to strings
+and every isinstance(..., list) consumer silently drops them.
+"""
+import pytest
+
+from hermes_state import SessionDB
+
+
+REASONING_DETAILS = [
+ {"type": "reasoning.text", "text": "compare both branches first", "format": "unknown"}
+]
+CODEX_REASONING_ITEMS = [
+ {"id": "rs_1", "type": "reasoning", "encrypted_content": "opaque-blob"}
+]
+CODEX_MESSAGE_ITEMS = [
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "done"}],
+ }
+]
+
+
+def db(tmp_path):
+ return SessionDB(tmp_path / "state.db")
+
+
+def _seed(db, sid="src"):
+ """Session with one assistant message carrying all three reasoning fields."""
+ db.create_session(sid, source="cli")
+ db.append_message(sid, role="user", content="hi")
+ db.append_message(
+ sid,
+ role="assistant",
+ content="done",
+ reasoning_details=REASONING_DETAILS,
+ codex_reasoning_items=CODEX_REASONING_ITEMS,
+ codex_message_items=CODEX_MESSAGE_ITEMS,
+ )
+
+
+def _fork(db, src, dst):
+ """The fork handler's copy step: raw get_messages rows into replace_messages."""
+ db.create_session(dst, source="cli")
+ db.replace_messages(dst, db.get_messages(src))
+
+
+def _assistant(conversation):
+ return next(m for m in conversation if m["role"] == "assistant")
+
+
+class TestDirectWrite:
+ """Live-runtime path: structured values in, structured values back."""
+
+ def test_reasoning_fields_hydrate_as_structures(self, db):
+ _seed(db)
+ msg = _assistant(db.get_messages_as_conversation("src"))
+ assert msg["reasoning_details"] == REASONING_DETAILS
+ assert msg["codex_reasoning_items"] == CODEX_REASONING_ITEMS
+ assert msg["codex_message_items"] == CODEX_MESSAGE_ITEMS
+
+
+class TestForkRoundTrip:
+ """get_messages -> replace_messages must keep the stored TEXT intact."""
+
+ def test_reasoning_details_survive_fork(self, db):
+ _seed(db)
+ _fork(db, "src", "fork")
+ msg = _assistant(db.get_messages_as_conversation("fork"))
+ assert msg["reasoning_details"] == REASONING_DETAILS
+
+ def test_codex_reasoning_items_survive_fork(self, db):
+ _seed(db)
+ _fork(db, "src", "fork")
+ msg = _assistant(db.get_messages_as_conversation("fork"))
+ assert msg["codex_reasoning_items"] == CODEX_REASONING_ITEMS
+
+ def test_codex_message_items_survive_fork(self, db):
+ _seed(db)
+ _fork(db, "src", "fork")
+ msg = _assistant(db.get_messages_as_conversation("fork"))
+ assert msg["codex_message_items"] == CODEX_MESSAGE_ITEMS
+
+ def test_fork_of_fork_stays_stable(self, db):
+ # Each extra round-trip used to add another encoding layer.
+ _seed(db)
+ _fork(db, "src", "fork1")
+ _fork(db, "fork1", "fork2")
+ msg = _assistant(db.get_messages_as_conversation("fork2"))
+ assert msg["reasoning_details"] == REASONING_DETAILS
+ assert msg["codex_reasoning_items"] == CODEX_REASONING_ITEMS
+ assert msg["codex_message_items"] == CODEX_MESSAGE_ITEMS
+
+
+class TestAppendMessageRoundTrip:
+ """append_message accepts a stored row's already-serialized TEXT too."""
+
+ def test_string_value_not_double_encoded(self, db):
+ _seed(db)
+ row = next(m for m in db.get_messages("src") if m["role"] == "assistant")
+ db.create_session("copy", source="cli")
+ db.append_message(
+ "copy",
+ role="assistant",
+ content="done",
+ reasoning_details=row["reasoning_details"],
+ )
+ msg = _assistant(db.get_messages_as_conversation("copy"))
+ assert msg["reasoning_details"] == REASONING_DETAILS
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index a5bbe23246c..2df2b124e37 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -16411,3 +16411,119 @@ def test_fallback_session_info_always_emits_branch(monkeypatch):
assert "branch" in info
assert info["branch"] == ""
+
+
+BRANCH_REASONING = "the parent's chain of thought"
+BRANCH_REASONING_CONTENT = "the parent's reasoning content"
+BRANCH_REASONING_DETAILS = [
+ {"type": "reasoning.text", "text": "keep the parent's plan", "format": "unknown"}
+]
+BRANCH_CODEX_REASONING_ITEMS = [
+ {"id": "rs_1", "type": "reasoning", "encrypted_content": "opaque-blob"}
+]
+BRANCH_CODEX_MESSAGE_ITEMS = [
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "done"}],
+ }
+]
+
+
+def _branch_history():
+ return [
+ {"role": "user", "content": "hello"},
+ {
+ "role": "assistant",
+ "content": "done",
+ "reasoning": BRANCH_REASONING,
+ "reasoning_content": BRANCH_REASONING_CONTENT,
+ "reasoning_details": BRANCH_REASONING_DETAILS,
+ "codex_reasoning_items": BRANCH_CODEX_REASONING_ITEMS,
+ "codex_message_items": BRANCH_CODEX_MESSAGE_ITEMS,
+ },
+ ]
+
+
+def _branched_assistant(db, session_key):
+ return next(
+ m
+ for m in db.get_messages_as_conversation(session_key)
+ if m["role"] == "assistant"
+ )
+
+
+def test_persist_branch_seed_keeps_reasoning_fields(monkeypatch, tmp_path):
+ """The seed write must carry the parent's reasoning fields.
+
+ A branch is a draft until its first submit, so this is the only write that
+ ever persists the copied transcript. Persisting role/content alone left the
+ branch resuming without the parent's reasoning, preserved thinking blocks or
+ Codex encrypted-reasoning/message-item continuation state.
+ """
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session = _session(
+ session_key="branch-key",
+ parent_session_id="parent-key",
+ history=_branch_history(),
+ )
+ try:
+ db.create_session("branch-key", source="tui")
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+
+ server._persist_branch_seed(session)
+
+ assistant = _branched_assistant(db, "branch-key")
+ assert assistant["reasoning"] == BRANCH_REASONING
+ assert assistant["reasoning_content"] == BRANCH_REASONING_CONTENT
+ assert assistant["reasoning_details"] == BRANCH_REASONING_DETAILS
+ assert assistant["codex_reasoning_items"] == BRANCH_CODEX_REASONING_ITEMS
+ assert assistant["codex_message_items"] == BRANCH_CODEX_MESSAGE_ITEMS
+ assert session["_branch_seed_persisted"] is True
+ finally:
+ db.close()
+
+
+def test_session_branch_keeps_reasoning_fields(monkeypatch, tmp_path):
+ """session.branch copies the live transcript with its reasoning fields.
+
+ Same drop as the seed path: the copy loop wrote only role/content, so the
+ new session row replayed without the reasoning context the parent had.
+ """
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ server._sessions["sid"] = _session(history=_branch_history())
+ try:
+ db.create_session("session-key", source="tui")
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ monkeypatch.setattr(server, "_new_session_key", lambda: "branch-key")
+ monkeypatch.setattr(server, "_start_agent_build", lambda sid, session: None)
+ monkeypatch.setattr(server, "_wait_agent", lambda session, rid: None)
+ monkeypatch.setattr(
+ server, "_claim_active_session_slot", lambda *args, **kwargs: (None, None)
+ )
+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")
+ monkeypatch.setattr(server, "_session_cwd", lambda session: str(tmp_path))
+ monkeypatch.setattr(
+ server, "_make_agent", lambda *args, **kwargs: types.SimpleNamespace()
+ )
+ monkeypatch.setattr(server, "_init_session", lambda *args, **kwargs: None)
+
+ resp = server.handle_request(
+ {"id": "1", "method": "session.branch", "params": {"session_id": "sid"}}
+ )
+
+ assert resp.get("result"), f"got error: {resp.get('error')}"
+ assistant = _branched_assistant(db, "branch-key")
+ assert assistant["reasoning"] == BRANCH_REASONING
+ assert assistant["reasoning_content"] == BRANCH_REASONING_CONTENT
+ assert assistant["reasoning_details"] == BRANCH_REASONING_DETAILS
+ assert assistant["codex_reasoning_items"] == BRANCH_CODEX_REASONING_ITEMS
+ assert assistant["codex_message_items"] == BRANCH_CODEX_MESSAGE_ITEMS
+ finally:
+ server._sessions.pop("sid", None)
+ db.close()
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 0222b8c2f51..1e0b41254a8 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -2820,6 +2820,11 @@ def _(rid, params: dict) -> dict:
{
"role": msg.get("role", "user"),
"content": msg.get("content"),
+ "reasoning": msg.get("reasoning"),
+ "reasoning_content": msg.get("reasoning_content"),
+ "reasoning_details": msg.get("reasoning_details"),
+ "codex_reasoning_items": msg.get("codex_reasoning_items"),
+ "codex_message_items": msg.get("codex_message_items"),
# Preserve the parent's original message timestamps —
# branch copies are history, not new activity (9d73006ad).
"timestamp": msg.get("timestamp"),
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 4a57a98be6d..c33cba50ea9 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2864,6 +2864,11 @@ def _persist_branch_seed(session: dict) -> None:
{
"role": msg.get("role", "user"),
"content": msg.get("content"),
+ "reasoning": msg.get("reasoning"),
+ "reasoning_content": msg.get("reasoning_content"),
+ "reasoning_details": msg.get("reasoning_details"),
+ "codex_reasoning_items": msg.get("codex_reasoning_items"),
+ "codex_message_items": msg.get("codex_message_items"),
# Preserve the parent's original message timestamps —
# append_message would otherwise stamp time.time() and the
# branch's copied history would all appear authored "now".