The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /rollback lists, diffs and restores the gateway's checkpoints (rollback.*)
Tekniuma1611b690f26
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 1bd5ccd7834..480ded44842 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -539,6 +539,11 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):"""Handle /rollback [diff] <N> [<file>|--all] — list, diff, or restore checkpoints.A restore also undoes the last chat turn; ``--all`` overwrites user hand-edits too."""from tools.checkpoint_manager import format_checkpoint_list+ from hermes_cli.gateway_side import connection_for+ if (connection := connection_for(self)) is not None:+ # Checkpoints are taken by the gateway's tools: list/diff/restore are the owner's.+ from hermes_cli.gateway_rollback import rollback+ return rollback(self, connection, command)mgr = self._checkpoint_manager(_lines(_t("rollback.not_enabled")))if mgr is None:returndiff --git a/hermes_cli/gateway_rollback.py b/hermes_cli/gateway_rollback.pynew file mode 100644index 00000000000..f76a6527824--- /dev/null+++ b/hermes_cli/gateway_rollback.py@@ -0,0 +1,76 @@+"""``/rollback`` on the shared gateway session (``rollback.list`` / ``rollback.diff`` / ``rollback.restore``).++The gateway's tools take the checkpoints (its ``CheckpointManager``, keyed by the session's launch+cwd), so the CLI process has no manager of its own: it renders main's text over the owner's+answers. A whole-tree restore also rewinds the newest user turn on the owner (``history_removed``);+the CLI then re-reads the transcript so its warm history matches.+"""+from __future__ import annotations++import os++from agent.i18n import t+from hermes_cli.gateway_client import GatewayClientError+++def _t(key, **kw):+ return t(f"cli.commands.{key}", **kw)+++def _checkpoint_rows(result):+ """``rollback.list`` rows as ``format_checkpoint_list`` reads them."""+ return [{"hash": c.get("hash", ""), "short_hash": (c.get("hash") or "")[:7], "timestamp": c.get("timestamp", ""),+ "reason": c.get("message", "")} for c in result.get("checkpoints") or []]+++def rollback(cli, connection, command):+ from tools.checkpoint_manager import format_checkpoint_list+ args = [a for a in command.split()[1:] if a.lower() not in ("--all", "--force")]+ cwd = os.getenv("TERMINAL_CWD", os.getcwd())+ sid = cli.session_id+ try:+ if not args:+ listed = connection.call("rollback.list", session_id=sid)+ if not listed.get("enabled"):+ return print("\n".join(f" {line}" if line else "" for line in _t("rollback.not_enabled").splitlines()))+ return print(format_checkpoint_list(_checkpoint_rows(listed), cwd))+ if args[0].lower() == "diff":+ if len(args) < 2:+ return print(f" {_t('rollback.usage_diff')}")+ return _diff(connection.call("rollback.diff", session_id=sid, hash=args[1]))+ params = {"session_id": sid, "hash": args[0]}+ if len(args) > 1:+ params["file_path"] = args[1]+ _restored(cli, connection, connection.call("rollback.restore", **params), params.get("file_path"))+ except GatewayClientError as exc:+ print(f" ❌ {exc}")+++def _diff(result):+ stat, diff = result.get("stat", ""), result.get("diff", "")+ if not stat and not diff:+ return print(f" {_t('rollback.no_changes_since')}")+ if stat:+ print(f"\n{stat}")+ if diff:+ lines = diff.splitlines()+ if len(lines) > 80: # main's terminal-flood limit+ print("\n".join(lines[:80]))+ print(f"\n {_t('rollback.more_lines', count=len(lines) - 80)}")+ else:+ print(f"\n{diff}")+++def _restored(cli, connection, result, file_path):+ if not result.get("success"):+ return print(f" ❌ {result.get('error')}")+ restored = {"hash": result.get("restored_to", ""), "reason": result.get("reason", "")}+ print(f" {_t('rollback.restored_file', file=file_path, **restored)}" if file_path+ else f" {_t('rollback.restored_all', **restored)}")+ print(f" {_t('rollback.snapshot_saved')}")+ if result.get("history_removed"):+ snapshot = connection.call("session.resume", session_id=cli.session_id)+ connection.state(cli.session_id).adopt_snapshot(snapshot)+ cli.conversation_history = [{k: v for k, v in m.items() if k != "row_id"}+ for m in snapshot.get("messages") or []]+ print(f" {_t('rollback.chat_turn_undone')}")diff --git a/tests/hermes_cli/test_gateway_rollback.py b/tests/hermes_cli/test_gateway_rollback.pynew file mode 100644index 00000000000..7830b034fea--- /dev/null+++ b/tests/hermes_cli/test_gateway_rollback.py@@ -0,0 +1,53 @@+"""/rollback on the shared gateway: the checkpoints are the gateway's, so list/diff/restore go to+the owner's ``rollback.*`` verbs and print main's text (the CLI process has no manager)."""+import asyncio+from contextlib import asynccontextmanager++from hermes_cli import gateway_rollback+from hermes_cli.gateway_connection import GatewayConnection+++class _Client:+ def __init__(self, answers):+ self.events = asyncio.Queue()+ self.calls = []+ self.answers = answers++ async def rpc(self, method, *, _timeout=None, **params):+ self.calls.append((method, params))+ return self.answers[method]+++def _connection(client):+ @asynccontextmanager+ async def connect():+ yield client+ conn = GatewayConnection(connect=connect)+ conn.start(5)+ return conn+++class _Cli:+ session_id = "local-rb"+ conversation_history = [{"role": "user", "content": "old"}]+++def test_rollback_lists_and_restores_through_the_gateway(capsys, monkeypatch, tmp_path):+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))+ client = _Client({+ "rollback.list": {"enabled": True, "checkpoints": [+ {"hash": "3101637abcdef", "timestamp": "2026-10-13T11:25:00+00:00", "message": "before write_file"}]},+ "rollback.restore": {"success": True, "restored_to": "3101637", "reason": "before write_file",+ "history_removed": 2},+ "session.resume": {"revision": 3, "execution_generation": 1, "messages": []}})+ conn = _connection(client)+ cli = _Cli()+ try:+ gateway_rollback.rollback(cli, conn, "/rollback")+ out = capsys.readouterr().out+ assert "1. 3101637" in out and "before write_file" in out, out+ gateway_rollback.rollback(cli, conn, "/rollback 1")+ assert ("rollback.restore", {"session_id": "local-rb", "hash": "1"}) in client.calls+ assert cli.conversation_history == [] # the owner's rewound transcript+ finally:+ conn.close()