The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /undo and /retry rewind the gateway transcript by the turn's durable row id
Teknium572783480709
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 2b280c9a79d..22811c4d372 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -161,6 +161,45 @@ class GatewaySessionStore:self.connection.state(session_id).title = titlereturn True+ def rewind_user_turn(self, session_id, user_ordinal, *, warm_history=None, require_retryable=False, **_kw):+ """Main's ``SessionDB.rewind_user_turn`` (``/undo N``, ``/retry``) as ``session.mutate rewind``.+ The user turn is located on the gateway's snapshot transcript (its rows carry ``row_id``),+ checked against the CLI's warm view exactly as main checks it, then rewound by that row id."""+ from agent.context_compressor import history_before_user_originated_turn, retryable_user_text+ from agent.message_content import flatten_message_text+ from agent.session_persistence import _is_ephemeral_scaffolding+ from hermes_state_rewind import (+ _HISTORY_CHANGED, RewindOutcome, RewindTargetUnavailableError, _comparison_content, _user_indices)+ snapshot = self.call("session.resume", session_id=session_id)+ durable = list(snapshot.get("messages") or [])+ durable_user = _user_indices(durable)+ if user_ordinal < 0:+ user_ordinal = max(len(durable_user) + user_ordinal, 0)+ if user_ordinal >= len(durable_user):+ raise RewindTargetUnavailableError("target user message is no longer in session history")+ target = durable[durable_user[user_ordinal]]+ durable_prefix, live_view = history_before_user_originated_turn(durable, durable_user[user_ordinal])+ prefix = [{k: v for k, v in m.items() if k != "row_id"} for m in durable_prefix]+ if warm_history is not None:+ warm = [m for m in warm_history if not _is_ephemeral_scaffolding(m)]+ warm_user = _user_indices(warm)+ if len(warm_user) != len(durable_user):+ raise RuntimeError(_HISTORY_CHANGED)+ prefix, warm_live = history_before_user_originated_turn(warm, warm_user[user_ordinal])+ if _comparison_content(live_view) != _comparison_content(warm_live):+ raise RuntimeError(_HISTORY_CHANGED)+ live_text = retryable_user_text(live_view.get("content")) if require_retryable else None+ if not isinstance(target.get("row_id"), int):+ raise RuntimeError("rewind target has no durable row identity")+ receipt = self.call("session.mutate", session_id=session_id, request_id=uuid.uuid4().hex,+ expected_revision=snapshot["revision"],+ expected_generation=snapshot["execution_generation"],+ operation="rewind", payload={"target_message_id": target["row_id"]}) or {}+ 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")),+ rewound_count=int(receipt.get("rewound_count") or 0), turns_undone=len(durable_user) - user_ordinal)+def _title_holder(self, session_id, title):db = self._db()if db is None or not title:diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex a163becced3..daa544dc9e6 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -118,7 +118,7 @@ def test_gateway_owned_writes_are_noops_and_unknown_writes_refuse(store):assert db.prune_empty_ghost_sessions() == 0assert len(client.calls) == beforewith pytest.raises(ValueError):- db.rewind_user_turn("x", 1)+ db.request_handoff("x", "telegram")def test_banner_inventory_comes_from_the_session_snapshot(store):@@ -208,3 +208,49 @@ def test_rename_refusal_prints_mains_title_in_use_text(store, tmp_path, monkeypawith pytest.raises(ValueError) as err:db.set_session_title("local-old", "Free Title")assert str(err.value) == "request_failed"+++HISTORY = [{"role": "user", "content": "one", "row_id": 11}, {"role": "assistant", "content": "a1", "row_id": 12},+ {"role": "user", "content": "two", "row_id": 13}, {"role": "assistant", "content": "a2", "row_id": 14}]+++def _with_history(client):+ base = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ if method == "session.resume":+ client.calls.append((method, params))+ return {**snapshot(params["session_id"]), "messages": [dict(m) for m in HISTORY],+ "execution_generation": 7}+ if method == "session.mutate" and params["operation"] == "rewind":+ client.calls.append((method, params))+ return {"rewound_count": 2, "target_message": {"role": "user", "content": "two"}}+ return await base(method, _timeout=_timeout, **params)+ client.rpc = rpc+++def test_undo_and_retry_rewind_by_the_durable_row_id(store):+ """main's ``rewind_user_turn(sid, ordinal, warm_history=...)`` as ``session.mutate rewind``+ addressed by the row id of that user turn in the gateway's snapshot."""+ db, client = store+ _with_history(client)+ db.open_session(cli("local-old", resumed=True))+ warm = [{k: v for k, v in m.items() if k != "row_id"} for m in HISTORY]+ outcome = db.rewind_user_turn("local-old", 1, warm_history=warm)+ mutate = [p for m, p in client.calls if m == "session.mutate"][-1]+ assert mutate["operation"] == "rewind" and mutate["payload"] == {"target_message_id": 13}+ assert mutate["expected_generation"] == 7+ assert outcome.prefix == warm[:2] and outcome.live_text == "two" and outcome.rewound_count == 2+ retry = db.rewind_user_turn("local-old", -1, warm_history=warm, require_retryable=True)+ assert [p for m, p in client.calls if m == "session.mutate"][-1]["payload"] == {"target_message_id": 13}+ assert retry.live_text == "two" and retry.turns_undone == 1+++def test_rewind_refuses_when_the_warm_view_diverged(store):+ db, client = store+ _with_history(client)+ db.open_session(cli("local-old", resumed=True))+ before = len([c for c in client.calls if c[0] == "session.mutate"])+ with pytest.raises(RuntimeError):+ db.rewind_user_turn("local-old", -1, warm_history=[{"role": "user", "content": "other"}])+ assert len([c for c in client.calls if c[0] == "session.mutate"]) == before