Skip to content

The agent that grows with you

fix(gateway): rollback.restore keeps hand-edits unless --all, like the other /rollback paths

arcabotai0c8d4b7363c9
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 408f6110a56..5a1b20b922f 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3865,6 +3865,7 @@ export interface RollbackRestoreParams {
hash: string
file_path?: string | null
profile?: string | null
+ all?: boolean | null
}
/** ``tools/checkpoint_manager.py::restore`` outcome; ``history_removed`` is added for a full (non-file) restore that also rewound the live transcript. */
export interface RollbackRestoreResult {
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 40cfed7af53..5c5208842a1 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -32854,6 +32854,18 @@
],
"default": null,
"title": "Profile"
+ },
+ "all": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "All"
}
},
"required": [
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.py
index 66058674afd..1504ec4361b 100644
--- a/gateway/session_tui_ops.py
+++ b/gateway/session_tui_ops.py
@@ -142,7 +142,7 @@ async def pause_delegation(connection, ref, params):
_ROLLBACK_FIELDS = {'list': {'session_id', 'profile'}, 'diff': {'session_id', 'profile', 'hash'},
- 'restore': {'session_id', 'profile', 'hash', 'file_path'},
+ 'restore': {'session_id', 'profile', 'hash', 'file_path', 'all'},
'session_diff': {'session_id', 'profile'}}
# ``rollback.session_diff`` body bound: well inside one 8 MiB frame (the classic CLI shows 400 lines).
_SESSION_DIFF_CHARS = 2 * 1024 * 1024
@@ -159,7 +159,8 @@ async def rollback(connection, ref, params, *, kind):
(main's ``_rewind_active_session_history``) through the owner's fenced ``rewind`` mutation."""
fields = _ROLLBACK_FIELDS[kind]
if any(key in params and (not isinstance(params[key], str) or (key == 'hash' and not params[key]))
- for key in ('hash', 'file_path')) or (kind in ('diff', 'restore') and 'hash' not in params):
+ for key in ('hash', 'file_path')) or (kind in ('diff', 'restore') and 'hash' not in params) or (
+ not isinstance(params.get('all', False), bool)):
raise RuntimeStoreError('invalid_params')
live = _live_ref(connection, ref, params, fields, 'session:read' if kind != 'restore' else 'session:control')
authority = connection.authority
@@ -218,7 +219,9 @@ async def rollback(connection, ref, params, *, kind):
return payload
if refusal:
return {'success': False, 'error': refusal}
- return mgr.restore(cwd, target, file_path=file_path or None)
+ # Main's whole-tree /rollback keeps the user's hand-edits unless ``--all`` (``all``) says otherwise.
+ return mgr.restore(cwd, target, file_path=file_path or None,
+ safe=not file_path and not params.get('all'))
result = await asyncio.to_thread(run)
if kind == 'restore' and result.get('success') and not file_path:
result['history_removed'] = await _rewind_last_turn(connection, ref)
diff --git a/hermes_cli/gateway_rollback.py b/hermes_cli/gateway_rollback.py
index f76a6527824..5003b46eb7a 100644
--- a/hermes_cli/gateway_rollback.py
+++ b/hermes_cli/gateway_rollback.py
@@ -25,7 +25,9 @@ def _checkpoint_rows(result):
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")]
+ words = command.split()[1:]
+ args = [a for a in words if a.lower() not in ("--all", "--force")]
+ restore_all = len(args) != len(words)
cwd = os.getenv("TERMINAL_CWD", os.getcwd())
sid = cli.session_id
try:
@@ -41,6 +43,8 @@ def rollback(cli, connection, command):
params = {"session_id": sid, "hash": args[0]}
if len(args) > 1:
params["file_path"] = args[1]
+ elif restore_all:
+ params["all"] = True # main's --all/--force: also revert the user's hand-edits
_restored(cli, connection, connection.call("rollback.restore", **params), params.get("file_path"))
except GatewayClientError as exc:
print(f" ❌ {exc}")
@@ -67,6 +71,14 @@ def _restored(cli, connection, result, file_path):
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)}")
+ from hermes_cli.cli_commands_mixin import _summarize_paths
+ from hermes_cli.cli_commands_session_tools import _gt, _lines, _pr
+ if skipped := result.get("skipped_user_edits"):
+ _pr(*_lines(_gt("rollback.kept_user_edits", files=_summarize_paths(skipped))))
+ if oversize := result.get("skipped_oversize"):
+ print(f" {_gt('rollback.kept_oversize', files=_summarize_paths(oversize))}")
+ if failed := result.get("failed_deletes"):
+ print(f" {_gt('rollback.failed_deletes', files=_summarize_paths(failed))}")
print(f" {_t('rollback.snapshot_saved')}")
if result.get("history_removed"):
snapshot = connection.call("session.resume", session_id=cli.session_id)
diff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.py
index 567eadbc111..abee9caee0a 100644
--- a/tests/gateway/test_session_tui_ops.py
+++ b/tests/gateway/test_session_tui_ops.py
@@ -152,3 +152,45 @@ def test_rollback_lists_diffs_and_restores_the_session_cwd_and_rewinds_the_last_
bad = (await _git_rpc(ws, 'rollback.restore', session_id=sid, hash='9'))['result']
assert bad['success'] is False and 'Invalid checkpoint number' in bad['error'], bad
asyncio.run(probe())
+
+
+def _agent_write(home, path, text):
+ """A file write Hermes made (and recorded in the agent-write ledger that safe restore reads)."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from tools.checkpoint_manager import CheckpointManager
+ path.write_text(text)
+ token = set_hermes_home_override(str(home))
+ try:
+ CheckpointManager(enabled=True).record_agent_write(str(path))
+ finally:
+ reset_hermes_home_override(token)
+
+
+def test_rollback_restore_keeps_hand_edits_unless_all(tmp_path):
+ """The RPC's whole-tree restore is main's safe one (the help text's "restores keep your
+ hand-edits"); ``all`` is ``/rollback <N> --all``."""
+ with owner(tmp_path) as (home, _peer, desc):
+ work = tmp_path / 'work'
+ work.mkdir()
+ (work / 'agent.txt').write_text('original\n')
+ (work / 'mine.txt').write_text('original mine\n')
+
+ async def probe():
+ async with websocket(home, desc) as ws:
+ sid = (await rpc(ws, 'session.create', request_id='safe', source='tui', toolsets=[],
+ cwd=str(work), checkpoints=True))['result']['session_id']
+ await asyncio.to_thread(_checkpoint, home, work, 'before write_file')
+ [row] = (await _git_rpc(ws, 'rollback.list', session_id=sid))['result']['checkpoints']
+ await asyncio.to_thread(_agent_write, home, work / 'agent.txt', 'agent\n')
+ (work / 'mine.txt').write_text('hand edit\n')
+ assert (await rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash'],
+ all='maybe'))['error']['message'] == 'invalid_params'
+ safe = (await _git_rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash']))['result']
+ assert safe['success'] is True and safe['skipped_user_edits'] == ['mine.txt'], safe
+ assert (work / 'agent.txt').read_text() == 'original\n'
+ assert (work / 'mine.txt').read_text() == 'hand edit\n'
+ forced = (await _git_rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash'], all=True))['result']
+ assert forced['success'] is True and not forced.get('skipped_user_edits'), forced
+ assert (work / 'mine.txt').read_text() == 'original mine\n'
+ asyncio.run(probe())
diff --git a/tests/hermes_cli/test_gateway_rollback.py b/tests/hermes_cli/test_gateway_rollback.py
index 7830b034fea..24815aca5b7 100644
--- a/tests/hermes_cli/test_gateway_rollback.py
+++ b/tests/hermes_cli/test_gateway_rollback.py
@@ -51,3 +51,25 @@ def test_rollback_lists_and_restores_through_the_gateway(capsys, monkeypatch, tm
assert cli.conversation_history == [] # the owner's rewound transcript
finally:
conn.close()
+
+
+def test_rollback_all_reaches_the_gateway_and_kept_edits_are_shown(capsys, monkeypatch, tmp_path):
+ """The owner's whole-tree restore keeps hand-edits by default: the CLI says which, and its
+ ``--all``/``--force`` override travels as ``all`` instead of being dropped."""
+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))
+ client = _Client({
+ "rollback.restore": {"success": True, "restored_to": "3101637", "reason": "before write_file",
+ "skipped_user_edits": ["notes.md"]}})
+ conn = _connection(client)
+ cli = _Cli()
+ try:
+ gateway_rollback.rollback(cli, conn, "/rollback 1")
+ assert client.calls[-1] == ("rollback.restore", {"session_id": "local-rb", "hash": "1"})
+ out = capsys.readouterr().out
+ assert "notes.md" in out and "--all" in out, out
+ gateway_rollback.rollback(cli, conn, "/rollback 1 --all")
+ assert client.calls[-1] == ("rollback.restore", {"session_id": "local-rb", "hash": "1", "all": True})
+ gateway_rollback.rollback(cli, conn, "/rollback 1 a.txt --force")
+ assert client.calls[-1] == ("rollback.restore", {"session_id": "local-rb", "hash": "1", "file_path": "a.txt"})
+ finally:
+ conn.close()
diff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.py
index 7acf9b86f59..3c1c6596140 100644
--- a/tui_gateway/contracts/tools_commands.py
+++ b/tui_gateway/contracts/tools_commands.py
@@ -389,6 +389,9 @@ class RollbackRestoreParams(Params):
hash: str
file_path: str | None = None
profile: str | None = None
+ # A whole-tree restore keeps the user's hand-edits (``CheckpointManager.restore(safe=True)``, as the
+ # gateway text command and the in-process CLI do); ``all`` reverts them too (main's ``--all``).
+ all: bool | None = None
class RollbackRestoreResult(_Open):