Skip to content

The agent that grows with you

fix(cli): restore snapshots through an offline gateway handoff

kassdin44248a0b3932
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index dce85369e58..f382c193322 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -614,37 +614,8 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
else f" {_t('snapshot.nothing_to_snapshot')}")
def _snapshot_restore(self, parts) -> None:
- from hermes_cli.backup import list_quick_snapshots, restore_quick_snapshot
- if len(parts) < 3:
- print(f" {_t('snapshot.usage_restore')}")
- snaps = list_quick_snapshots(limit=1)
- if snaps:
- print(f" {_t('snapshot.most_recent', snapshot_id=snaps[0]['id'])}")
- return
- snap_id = parts[2]
- try:
- idx = int(snap_id) # restore by number (1-indexed)
- except ValueError:
- idx = None
- if idx is not None:
- snaps = list_quick_snapshots()
- if not 1 <= idx <= len(snaps):
- return print(f" {_t('snapshot.invalid_number', max=len(snaps))}")
- snap_id = snaps[idx - 1]["id"]
- # Close our own SessionDB first (restore contention); an open gateway session's store must stay.
- local_session_db = getattr(self, "_session_db", None)
- if local_session_db is not None and not getattr(self, "_gateway_session_open", False):
- with suppress(Exception):
- local_session_db.close()
- self._session_db = None
- if restore_quick_snapshot(snap_id):
- _pr(f" {_t('snapshot.restored', snapshot_id=snap_id)}",
- f" {_t('snapshot.restart_recommended')}")
- elif snap_id in {s.get("id") for s in list_quick_snapshots(limit=10**6)}:
- # False also means the auth.json merge was refused; don't call an existing snapshot missing.
- print(f" {_t('snapshot.restore_incomplete', snapshot_id=snap_id)}")
- else:
- print(f" {_t('snapshot.not_found', snapshot_id=snap_id)}")
+ from hermes_cli.cli_snapshot import restore_snapshot_command
+ restore_snapshot_command(self, parts)
def _snapshot_prune(self, parts) -> None:
from hermes_cli.backup import prune_quick_snapshots
diff --git a/hermes_cli/cli_snapshot.py b/hermes_cli/cli_snapshot.py
new file mode 100644
index 00000000000..4ea485af48e
--- /dev/null
+++ b/hermes_cli/cli_snapshot.py
@@ -0,0 +1,145 @@
+"""Classic CLI snapshot restore: hand off the profile offline, then rejoin its authority."""
+from __future__ import annotations
+
+from contextlib import suppress
+import logging
+import os
+
+from hermes_cli.cli_commands_session_tools import _pr, _t
+from hermes_cli.gateway_client import GatewayClientError
+
+logger = logging.getLogger(__name__)
+
+
+def restore_snapshot_command(cli, parts):
+ from hermes_cli.backup import list_quick_snapshots, restore_quick_snapshot
+ from hermes_cli.gateway_tools_notify import gateway_store
+ if len(parts) < 3:
+ print(f" {_t('snapshot.usage_restore')}")
+ snaps = list_quick_snapshots(limit=1)
+ if snaps:
+ print(f" {_t('snapshot.most_recent', snapshot_id=snaps[0]['id'])}")
+ return
+ snap_id = parts[2]
+ try:
+ idx = int(snap_id)
+ except ValueError:
+ idx = None
+ if idx is not None:
+ snaps = list_quick_snapshots()
+ if not 1 <= idx <= len(snaps):
+ return print(f" {_t('snapshot.invalid_number', max=len(snaps))}")
+ snap_id = snaps[idx - 1]["id"]
+ store = gateway_store(cli)
+ gateway = store is not None and getattr(cli, "_gateway_session_open", False)
+ try:
+ if gateway and _local_snapshot_exists(snap_id):
+ restored = _restore_gateway_snapshot(cli, store, snap_id)
+ else:
+ local_db = getattr(cli, "_session_db", None)
+ if local_db is not None and not gateway:
+ with suppress(Exception):
+ local_db.close()
+ cli._session_db = None
+ restored = restore_quick_snapshot(snap_id)
+ except (GatewayClientError, OSError) as exc:
+ logger.warning("Snapshot restore failed: %s", exc, exc_info=True)
+ return _pr(f" {_t('snapshot.restore_incomplete', snapshot_id=snap_id)}", f" {exc}")
+ if restored:
+ print(f" {_t('snapshot.restored', snapshot_id=snap_id)}")
+ if not gateway:
+ print(f" {_t('snapshot.restart_recommended')}")
+ elif snap_id in {s.get("id") for s in list_quick_snapshots(limit=10**6)}:
+ print(f" {_t('snapshot.restore_incomplete', snapshot_id=snap_id)}")
+ else:
+ print(f" {_t('snapshot.not_found', snapshot_id=snap_id)}")
+
+
+def _local_snapshot_exists(snap_id):
+ """An invalid/missing target must not take a working gateway offline."""
+ from hermes_cli.backup import _quick_snapshot_root
+ root = _quick_snapshot_root()
+ if not snap_id or "/" in snap_id or "\\" in snap_id or snap_id in {".", ".."}:
+ return False
+ target = root / snap_id
+ return target.resolve().is_relative_to(root.resolve()) and (target / "manifest.json").is_file()
+
+
+def _pause_owner(home, control_home):
+ from gateway.control_socket import pause_gateway_for_update, request_unserve_profile
+ if control_home != home:
+ ack = request_unserve_profile(control_home, home.name)
+ accepted = ack is not None and (ack.get("unserved") == home.name or ack.get("pending"))
+ else:
+ ack = pause_gateway_for_update(control_home, timeout=8)
+ accepted = ack is not None and ack.get("pausing")
+ if not accepted:
+ raise GatewayClientError("Gateway refused the snapshot maintenance handoff; nothing was restored. "
+ "Stop the gateway and retry.")
+
+
+def _restore_gateway_snapshot(cli, store, snap_id):
+ from gateway.control_socket import request_serve_profile_hot
+ from hermes_cli.backup import restore_quick_snapshot
+ from hermes_cli.gateway_connection import GatewayConnection
+ from hermes_cli.gateway_runtime import control_home_for, discover_gateway_endpoint
+ from hermes_cli.profiles_remove import wait_profile_unowned
+ from hermes_constants import get_hermes_home
+ from hermes_state_registry import close_all_under
+ if os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip():
+ raise GatewayClientError("Snapshot restore needs the local gateway. Disconnect the remote gateway and retry.")
+ home = get_hermes_home().resolve()
+ observed = discover_gateway_endpoint(home)
+ if observed.state != "ready" or observed.endpoint is None:
+ raise GatewayClientError("Local gateway is not ready for snapshot maintenance. Reconnect and retry.")
+ control_home = control_home_for(home, observed.endpoint).resolve()
+ store.close_reader()
+ close_all_under(home)
+ # A final viewer cannot redial from an idle poll while maintenance is replacing its database.
+ store.connection.close()
+ unserved = False
+ try:
+ _pause_owner(home, control_home)
+ unserved = control_home != home
+ if not wait_profile_unowned(home):
+ raise GatewayClientError("Gateway still owns the profile; nothing was restored. "
+ "Wait for its running work to stop and retry.")
+ return restore_quick_snapshot(snap_id)
+ finally:
+ if unserved:
+ ack = request_serve_profile_hot(control_home, home.name)
+ if ack is None or ack.get("error"):
+ logger.warning("Profile re-serve after snapshot restore: %s", ack)
+ store.snapshots.clear()
+ store.current = None
+ store.connection = GatewayConnection.shared()
+ _rejoin_cli(cli, store)
+
+
+def _rejoin_cli(cli, store):
+ from hermes_cli.cli_init_mixin import _ROUTE_FLAGS, _gateway_launch
+ from hermes_cli.gateway_tools import bind_session
+ # Same-id restores still replace the connection and invalidate the cached proxies.
+ cli.agent = None
+ for attr in ("_goal_manager", "_loop_manager", "_heartbeat_manager"):
+ setattr(cli, attr, None)
+ try:
+ snapshot = store.attach(cli.session_id)
+ except GatewayClientError as exc:
+ if str(exc) != "not_found":
+ raise
+ # The snapshot predates this session: only the owner may mint its replacement.
+ launch = {key: value for key, value in _gateway_launch(cli).items() if key not in _ROUTE_FLAGS}
+ store.create(launch, record_cwd=False)
+ snapshot = store.current
+ sid = snapshot["stored_session_id"]
+ held = sid != cli.session_id and getattr(cli, "_active_session_lease", None) is not None
+ if held:
+ cli._release_active_session()
+ cli.session_id = sid
+ cli.conversation_history = [{key: value for key, value in message.items() if key != "row_id"}
+ for message in snapshot.get("messages") or []]
+ bind_session(cli, store.connection)
+ if held and not cli._claim_active_session("cli", stderr=True):
+ raise GatewayClientError("session_already_owned")
+ getattr(cli, "_write_terminal_breadcrumb", lambda: None)()
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 70c3662825a..5f716698976 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -74,6 +74,12 @@ class GatewaySessionStore:
def __bool__(self):
return not self.connection.final
+ def close_reader(self):
+ """Release this viewer's SQLite handles before offline maintenance; keep its RPC store."""
+ if self._reader is not None:
+ self._reader.close()
+ self._reader = None
+
# -- reads -----------------------------------------------------------------------------
def _db(self):
"""The read-only reader, opened on first use. No state.db yet (the gateway creates it on its
diff --git a/tests/hermes_cli/test_gateway_snapshot_restore_guards.py b/tests/hermes_cli/test_gateway_snapshot_restore_guards.py
new file mode 100644
index 00000000000..82215c41b03
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_snapshot_restore_guards.py
@@ -0,0 +1,113 @@
+"""Refused/failed CLI-16 restores never bypass ownership or abandon the CLI viewer."""
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli.backup import create_quick_snapshot
+from hermes_cli.cli_commands_mixin import CLICommandsMixin
+from hermes_cli.gateway_client import GatewayClientError
+from hermes_cli.gateway_connection import GatewayConnection, SessionState
+from hermes_cli.gateway_runtime import GatewayDiscovery, GatewayEndpoint
+from hermes_cli.gateway_session_store import GatewaySessionStore
+
+
+class _Connection:
+ def __init__(self, refusal=None):
+ self.final = False
+ self.states = {}
+ self.calls = []
+ self.refusal = refusal
+
+ def close(self):
+ self.final = True
+
+ def state(self, sid):
+ return self.states.setdefault(sid, SessionState(sid))
+
+ def call(self, method, **params):
+ self.calls.append(method)
+ if self.refusal:
+ raise GatewayClientError(self.refusal)
+ assert method == "session.resume"
+ return {"stored_session_id": "kept", "subscription_id": "fresh-subscription",
+ "revision": 4, "execution_generation": 2, "messages": [], "info": {}}
+
+
+def viewer(tmp_path, monkeypatch):
+ home = tmp_path / "state"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)
+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")
+ snapshot = create_quick_snapshot(hermes_home=home)
+ assert snapshot
+ old, fresh = _Connection(), _Connection()
+ store = GatewaySessionStore(old)
+ closed = []
+ store._reader = SimpleNamespace(close=lambda: closed.append(True))
+ store.snapshots["kept"] = {"subscription_id": "stale"}
+ cli = SimpleNamespace(_session_db=store, _gateway_session_open=True, session_id="kept",
+ agent=object(), conversation_history=[], model="fixture",
+ _goal_manager=object(), _loop_manager=object(), _heartbeat_manager=object())
+ endpoint = GatewayEndpoint(str(home), "owner", 5, 1, "http://127.0.0.1:1", "none",
+ frozenset({"session-authority-v1"}), str(home))
+ monkeypatch.setattr("hermes_cli.gateway_runtime.discover_gateway_endpoint",
+ lambda home: GatewayDiscovery("ready", endpoint))
+ monkeypatch.setattr(GatewayConnection, "shared", classmethod(lambda cls: fresh))
+ monkeypatch.setattr("hermes_cli.gateway_tools.bind_session", lambda *args: None)
+ monkeypatch.setattr("gateway.control_socket.pause_gateway_for_update", lambda *a, **kw: {"pausing": True})
+ monkeypatch.setattr("hermes_cli.profiles_remove.wait_profile_unowned", lambda home: True)
+ return cli, snapshot, old, fresh, closed
+
+
[email protected]("result", [False, "raise"])
+def test_failed_restore_still_rejoins_the_viewer(viewer, monkeypatch, result):
+ cli, snapshot, old, fresh, closed = viewer
+
+ def restore(sid):
+ assert old.final and closed == [True]
+ if result == "raise":
+ raise OSError("fixture restore refused")
+ return result
+
+ monkeypatch.setattr("hermes_cli.backup.restore_quick_snapshot", restore)
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
+ assert cli._session_db.connection is fresh
+ assert fresh.calls == ["session.resume"]
+ assert cli._session_db.current["subscription_id"] == "fresh-subscription"
+ assert cli.agent is None
+ assert cli._goal_manager is cli._loop_manager is cli._heartbeat_manager is None
+
+
[email protected]("boundary", ["refused", "still-owned"])
+def test_handoff_must_release_the_owner_before_restoring(viewer, monkeypatch, boundary):
+ cli, snapshot, old, fresh, closed = viewer
+ if boundary == "refused":
+ monkeypatch.setattr("gateway.control_socket.pause_gateway_for_update", lambda *a, **kw: None)
+ else:
+ monkeypatch.setattr("hermes_cli.profiles_remove.wait_profile_unowned", lambda home: False)
+
+ def forbidden_restore(sid):
+ raise AssertionError("restore must not run before ownership is released")
+
+ monkeypatch.setattr("hermes_cli.backup.restore_quick_snapshot", forbidden_restore)
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
+ assert old.final and closed == [True]
+ assert cli._session_db.connection is fresh and fresh.calls == ["session.resume"]
+
+
+def test_resume_authorization_refusal_never_creates_another_session(viewer, monkeypatch):
+ cli, snapshot, _old, fresh, _closed = viewer
+ fresh.refusal = "permission_denied"
+ monkeypatch.setattr("hermes_cli.backup.restore_quick_snapshot", lambda sid: True)
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
+ assert fresh.calls == ["session.resume"]
+ assert cli.session_id == "kept" and cli._session_db.connection is fresh
+
+
[email protected]("target", ["missing", "../outside", "0", "99999"])
+def test_invalid_target_does_not_disconnect_the_gateway(viewer, target):
+ cli, _snapshot, old, fresh, closed = viewer
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", target])
+ assert not old.final and closed == [] and fresh.calls == []
diff --git a/tests/hermes_cli/test_gateway_snapshot_restore_live.py b/tests/hermes_cli/test_gateway_snapshot_restore_live.py
new file mode 100644
index 00000000000..2f4ba0ef226
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_snapshot_restore_live.py
@@ -0,0 +1,180 @@
+"""CLI-16 in #134889: restore offline, then keep chatting on the restored authority."""
+from contextlib import closing
+from http.server import ThreadingHTTPServer
+import json
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+import threading
+from types import SimpleNamespace
+import uuid
+
+import pytest
+
+from hermes_cli.backup import create_quick_snapshot, restore_quick_snapshot
+from hermes_cli.cli_commands_mixin import CLICommandsMixin
+from hermes_cli.cli_init_mixin import CLIInitMixin
+from hermes_cli.gateway_connection import GatewayConnection
+from hermes_cli.gateway_runtime import discover_gateway_endpoint
+from hermes_cli.gateway_session_store import GatewaySessionStore
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env
+from tests.waiting import wait_until
+
+
+def local_gateway(tmp_path, monkeypatch):
+ """Only replace process launch: sockets, authority, SQLite restore and model I/O are real."""
+ user = tmp_path / "user"
+ user.mkdir()
+ peer = ThreadingHTTPServer(("127.0.0.1", 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f"http://127.0.0.1:{peer.server_port}/v1"
+ for key, value in {"OPENAI_API_KEY": "loopback-only", "OPENAI_BASE_URL": url}.items():
+ monkeypatch.setenv(key, value)
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: user))
+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)
+ root = Path(__file__).resolve().parents[2]
+ children, logs = [], []
+
+ def spawn(home, *, deadline, idle_exit=False):
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=url,
+ # This child owns a disposable default root; it is reaped below.
+ HERMES_STATE_DB_GUARD_BYPASS="1")
+ log = (home / f"fixture-gateway-{len(children)}.log").open("w+", encoding="utf-8")
+ logs.append(log)
+ process = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ children.append(process)
+ return process
+
+ monkeypatch.setattr("hermes_cli.gateway_runtime_start.spawn_unmanaged_gateway", spawn)
+ monkeypatch.setattr(GatewayConnection, "_shared", None)
+
+ def configure(multiplex):
+ home = user / ".hermes"
+ config = {"gateway": {"multiplex_profiles": multiplex},
+ "model": {"provider": "custom", "default": "fixture", "base_url": url},
+ "auxiliary": {"title_generation": {"enabled": False}},
+ "platform_toolsets": {"cli": []}}
+ homes = [home, home / "profiles" / "satellite"] if multiplex else [home]
+ for target in homes:
+ target.mkdir(parents=True, mode=0o700)
+ (target / "config.yaml").write_text(json.dumps(config), encoding="utf-8")
+ (target / ".env").write_text("OPENAI_API_KEY=loopback-only\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(homes[-1]))
+ return homes[-1]
+
+ try:
+ yield configure
+ finally:
+ connection = GatewayConnection._shared
+ if connection is not None:
+ connection.close()
+ for process in children:
+ if process.poll() is not None and process.returncode:
+ log = logs[children.index(process)]
+ log.seek(0)
+ print(log.read())
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=10)
+ for log in logs:
+ log.seek(0)
+ print(log.read()[-6000:])
+ log.close()
+ peer.release.set()
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+
+def _turn(store, session_id, text):
+ request_id = uuid.uuid4().hex
+ store.call("prompt.submit", session_id=session_id, input_id=request_id, text=text)
+ def settled():
+ with store._db()._read_ctx() as db:
+ row = db.execute("SELECT status FROM session_admissions WHERE request_id=?", (request_id,)).fetchone()
+ return row is not None and row[0] == "terminal"
+ wait_until(settled, timeout=40, interval=.05, what=f"gateway turn {text} to settle")
+ assert any(text in str(row.get("content")) and row.get("role") == "assistant"
+ for row in store.get_messages_as_conversation(session_id))
+
+
+def _epoch(store):
+ with store._db()._read_ctx() as db:
+ return db.execute("SELECT epoch FROM runtime_epoch WHERE singleton=1").fetchone()[0]
+
+
+def _default_profile_state(home):
+ path = home.parent.parent / "state.db"
+ with closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) as db:
+ return (db.execute("SELECT epoch FROM runtime_epoch WHERE singleton=1").fetchone(),
+ db.execute("SELECT id FROM sessions ORDER BY id").fetchall(),
+ db.execute("SELECT session_id,role,content FROM messages ORDER BY id").fetchall())
+
+
[email protected]("posix") # The fixture exercises the POSIX default/named profile layout.
[email protected]("multiplex", [False, True], ids=["standalone", "satellite"])
[email protected]("retained", [True, False], ids=["resume-restored", "create-missing"])
+def test_snapshot_restore_rejoins_the_restored_authority(local_gateway, multiplex, retained, capsys):
+ home = local_gateway(multiplex)
+ connection = GatewayConnection.shared()
+ store = GatewaySessionStore(connection)
+ sid = store.create({"toolsets": []})
+ _turn(store, sid, "BEFORE_SNAPSHOT")
+ snapshot = create_quick_snapshot(hermes_home=home)
+ assert snapshot
+ if not retained:
+ store.end_session(sid)
+ sid = store.create({"toolsets": []})
+ _turn(store, sid, "AFTER_SNAPSHOT")
+ # The direct API must still refuse a live owner, without rolling back its newer rows.
+ history_before = store.get_messages_as_conversation(sid)
+ assert not restore_quick_snapshot(snapshot, hermes_home=home)
+ assert store.get_messages_as_conversation(sid) == history_before
+ old_reader = store._reader
+ assert old_reader is not None
+ from hermes_state_registry import acquire
+ shared_reader = acquire(home / "state.db")
+ before = discover_gateway_endpoint(home).endpoint
+ assert before is not None
+ before_epoch = _epoch(store)
+ default_before = _default_profile_state(home) if multiplex else None
+ cli = SimpleNamespace(_session_db=store, _gateway_session_open=True, session_id=sid,
+ conversation_history=[{"role": "user", "content": "AFTER_SNAPSHOT"}],
+ agent=object(), model="fixture")
+
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
+
+ assert connection.final, capsys.readouterr().out
+ assert store.connection is not connection and not store.connection.final
+ assert old_reader._wrapped._conn is None and shared_reader._conn is None
+ assert cli.agent is None
+ assert (cli.session_id == sid) is retained
+ history = json.dumps(cli.conversation_history)
+ assert "AFTER_SNAPSHOT" not in history
+ assert ("BEFORE_SNAPSHOT" in history) is retained
+ state = store.connection.state(cli.session_id)
+ assert state.subscription_id and state.execution_generation is not None
+ after = discover_gateway_endpoint(home).endpoint
+ assert after is not None
+ assert _epoch(store) > before_epoch
+ if multiplex:
+ assert before.instance_id == after.instance_id
+ assert _default_profile_state(home) == default_before
+ else:
+ assert before.instance_id != after.instance_id
+ assert after.authority_epoch > before.authority_epoch
+ _turn(store, cli.session_id, "AFTER_RESTORE")
+ context = store.call("session.context_breakdown", session_id=cli.session_id)
+ assert context is not None
+ previous = cli.session_id
+ fresh = CLIInitMixin._new_session_id(cli, None)
+ assert fresh != previous
+ _turn(store, fresh, "AFTER_NEW")
diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.md
index f5016dc32bf..895fba92bc0 100644
--- a/website/docs/reference/slash-commands.md
+++ b/website/docs/reference/slash-commands.md
@@ -47,7 +47,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in
| `/compress [here [N] \| focus topic]` | Manually compress conversation context (flush memories + summarize). `/compress here [N]` summarizes everything except the most recent N exchanges (default 2), kept verbatim — pick your own compression boundary. A focus topic narrows what a full summary preserves. |
| `/rollback` | List or restore filesystem checkpoints (usage: /rollback [number]) |
| `/diff [staged\|all\|session] [--stat] [path...]` | Show git changes in the working directory. Default: unstaged changes plus untracked files. `staged` shows what's staged for commit, `all` everything since HEAD, and `session` the cumulative diff of everything Hermes changed here (from the earliest retained checkpoint baseline — requires checkpoints to be enabled; complements `/rollback diff <N>`). `--stat` prints just the changed-file summary; path arguments restrict the diff. |
-| `/snapshot [create\|restore <id>\|prune]` (alias: `/snap`) | Create or restore state snapshots of Hermes config/state. `create [label]` saves a snapshot, `restore <id>` reverts to it, `prune [N]` removes old snapshots, or list all with no args. Database restores write through SQLite's backup API so live processes (gateway, dashboard) see the restored data safely; if that path fails while another process still holds the database open, the restore refuses instead of risking corruption — stop the holder and retry. |
+| `/snapshot [create\|restore <id>\|prune]` (alias: `/snap`) | Create or restore state snapshots of Hermes config/state. `create [label]` saves a snapshot, `restore <id>` reverts to it, `prune [N]` removes old snapshots, or list all with no args. In classic `hermes chat`, restore closes the local readers and drains the local gateway before restoring offline, then reconnects with the restored history (or creates a new session if the snapshot predates it). A multiplexed secondary profile is stopped and re-served without restarting the other profiles; restoring the launch profile drains the whole gateway. Database restoration retains its exclusive-maintenance gate and SQLite backup safety checks: a holder that cannot be stopped still prevents restoration. |
| `/stop` | Kill all running background processes |
| `/queue <prompt>` (alias: `/q`) | Queue a prompt for the next turn (doesn't interrupt the current agent response). In the CLI, `/queue` with no arguments lists the pending queue, and `/queue list`, `/queue edit N <new prompt>`, `/queue rm N`, `/queue move A B`, and `/queue clear` inspect and manage queued prompts before they are sent. Prompts that begin with a management word can be force-queued with `/queue add <prompt>`. On the gateway's session, prompts queued mid-run live in the gateway's shared queue for the session: `list`/`rm`/`edit`/`clear` act on every prompt queued there (other windows' too), and `move` is refused for prompts the gateway holds, because it runs them in order. |
| `/steer <prompt>` | Inject a mid-run note that arrives at the agent **after the next tool call** — no interrupt, no new user turn. The text is appended to the last tool result's content once the current tool completes, giving the agent new context without breaking the current tool-calling loop. Use this to nudge direction mid-task (e.g. "focus on the auth module" while the agent is running tests). |
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md
index 71d56d07315..d6bb5b42130 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md
@@ -45,7 +45,7 @@ Hermes 有两个斜杠命令入口,均由 `hermes_cli/commands.py` 中的中
| `/title` | 为当前会话设置标题(用法:/title My Session Name) |
| `/compress [focus topic]` | 手动压缩对话上下文(刷新记忆 + 摘要)。可选的焦点主题可缩小摘要保留的范围。 |
| `/rollback` | 列出或恢复文件系统检查点(用法:/rollback [number]) |
-| `/snapshot [create\|restore <id>\|prune]`(别名:`/snap`) | 创建或恢复 Hermes 配置/状态的快照。`create [label]` 保存快照,`restore <id>` 回滚到该快照,`prune [N]` 删除旧快照,不带参数则列出所有快照。 |
+| `/snapshot [create\|restore <id>\|prune]`(别名:`/snap`) | 创建或恢复 Hermes 配置/状态的快照。`create [label]` 保存快照,`restore <id>` 回滚到该快照,`prune [N]` 删除旧快照,不带参数则列出所有快照。在经典 `hermes chat` 中,恢复会先关闭本地读取句柄、排空本地 Gateway,再离线恢复并重新连接:快照中仍有当前会话时载入恢复后的历史,否则创建新会话。多路复用中的非启动 profile 仅暂停并重新挂载自身,不重启其他 profile;恢复启动 profile 则会排空整个 Gateway。底层恢复仍保留独占维护门禁和 SQLite 安全检查,无法释放的占用仍会阻止恢复。 |
| `/stop` | 终止所有正在运行的后台进程 |
| `/queue <prompt>`(别名:`/q`) | 将 prompt(提示词)加入队列等待下一轮处理(不会中断当前 agent 响应)。 |
| `/steer <prompt>` | 在**下一次工具调用之后**向 agent 注入一条中途说明——不中断、不产生新的用户轮次。当前工具完成后,该文本会追加到最后一条工具结果的内容中,在不打断当前工具调用循环的情况下为 agent 提供新上下文。可用于在任务进行中调整方向(例如在 agent 运行测试时说"专注于 auth 模块")。 |