The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /save writes the gateway owner's export, not a client copy
kshitijk4poorb0a3189188cc
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.pyindex cc709099371..cc1c5802dc9 100644--- a/hermes_cli/cli_session_mixin.py+++ b/hermes_cli/cli_session_mixin.py@@ -135,6 +135,81 @@ def _apply_new_session_title(cli, title: str) -> Optional[str]:return sanitized+def _print_save_refusal(error) -> None:+ """A gateway's ``/save`` refusal: ``not_found`` (no stored conversation yet) is main's nothing-to-save."""+ print(t("cli.session.save_nothing") if str(error) == "not_found" else t("cli.session.save_failed", error=error))+++def _export_on_gateway(connection, session_id, fmt, filename, redact):+ """The owner's ``/save`` rendering of its stored row (``session.export``: the snapshot ``hermes+ sessions export`` writes, with title, metadata and archived rows), never this process's+ in-memory history. Nothing is written on the gateway host, so a remote owner's disk is never+ taken for this machine's. None when refused (printed), and also None when an older gateway+ without ``session.export`` was handed to ``_save_on_older_gateway`` (which may save on the+ gateway host and prints its own outcome)."""+ from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError+ try:+ content = (connection.call("session.export", session_id=session_id, format=fmt,+ redact=redact) or {}).get("content")+ except GatewayClientError as e:+ if not (isinstance(e, GatewayRPCError) and (e.code == -32601 or str(e) == "unknown_method")):+ _print_save_refusal(e)+ return None+ _save_on_older_gateway(connection, session_id, fmt, filename, redact)+ return None+ if not isinstance(content, str):+ print(t("cli.session.save_failed", error="the gateway returned no export"))+ return None+ return content+++def _save_on_older_gateway(connection, session_id, fmt, filename, redact):+ """An owner without ``session.export``: its ``session.save`` writes default-named, unredacted+ JSON on the gateway host, so only a plain ``/save json`` may use it (as Desktop does)."""+ from hermes_cli.gateway_client import GatewayClientError+ if redact or fmt != "json" or filename:+ print("(._.) This gateway predates this CLI: only a plain /save json works until it restarts "+ "(it saves on the gateway host).")+ return+ try:+ saved = (connection.call("session.save", session_id=session_id) or {}).get("file")+ except GatewayClientError as e:+ _print_save_refusal(e)+ return+ print(f"(^_^)v Conversation saved on the gateway host: {saved}" if saved+ else t("cli.session.save_failed", error="the gateway returned no file"))+++def _write_save(session_id, fmt, filename, render):+ """Write a ``/save`` export on this machine: ``filename`` as typed (relative to the cwd), else+ ``sessions/saved/hermes_conversation_<ts>.<fmt>`` under this CLI's home."""+ from cli import datetime+ saved_dir = get_hermes_home() / "sessions" / "saved"+ try:+ saved_dir.mkdir(parents=True, exist_ok=True)+ except OSError as e:+ print(t("cli.session.save_dir_failed", path=saved_dir, error=e))+ return+ if filename:+ path = Path(filename).expanduser()+ if not path.is_absolute():+ path = Path.cwd() / path+ else:+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ path = saved_dir / f"hermes_conversation_{timestamp}.{fmt}"++ try:+ content = render()+ with open(path, "w", encoding="utf-8") as f:+ f.write(content)+ label = {"json": "JSON", "md": t("cli.session.format_markdown"), "html": "HTML"}[fmt]+ print(t("cli.session.save_ok", path=path, label=label))+ if session_id:+ print(f" {t('cli.session.save_resume_hint', session_id=session_id)}")+ except Exception as e: # health: allow BLE001 -- /save's user boundary (main's, moved here): any render/write failure is printed+ print(t("cli.session.save_failed", error=e))++class CLISessionMixin:"""Session lifecycle for the interactive CLI: new/resume/save, undo/retry rewinds, yolopersistence, manual compression, and exit summary."""@@ -626,7 +701,6 @@ class CLISessionMixin:the live session stays resumable regardless. ``redact`` runs the force-mode secretredaction pass before writing."""- from cli import datetimefrom hermes_cli.session_export import (SAVE_USAGE, load_save_snapshot, normalize_save_format, render_session_for_save)@@ -644,6 +718,16 @@ class CLISessionMixin:print(SAVE_USAGE)returnfilename = parts[1] if len(parts) > 1 else None+ from hermes_cli.gateway_tools_notify import gateway_store+ store = gateway_store(self)+ if store is not None: # the gateway owns the session: it renders its stored row, this machine writes it+ if not self.conversation_history: # as Ink: nothing said yet, nothing exported+ print(t("cli.session.save_nothing"))+ return+ content = _export_on_gateway(store.connection, self.session_id, fmt, filename, redact)+ if content is not None:+ _write_save(self.session_id, fmt, filename, lambda: content)+ return# Prefer the durable DB row (metadata + tool calls); fall back to in-memory history.# getattr: test doubles may not carry _session_db / session_id.@@ -670,36 +754,7 @@ class CLISessionMixin:from hermes_cli.session_export_md import redact_session_datasession_data = redact_session_data(session_data)-- saved_dir = get_hermes_home() / "sessions" / "saved"- try:- saved_dir.mkdir(parents=True, exist_ok=True)- except Exception as e:- print(t("cli.session.save_dir_failed", path=saved_dir, error=e))- return- if filename:- path = Path(filename).expanduser()- if not path.is_absolute():- path = Path.cwd() / path- else:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- path = saved_dir / f"hermes_conversation_{timestamp}.{fmt}"-- try:- content = render_session_for_save(session_data, fmt)- with open(path, "w", encoding="utf-8") as f:- f.write(content)- label = {"json": "JSON", "md": t("cli.session.format_markdown"), "html": "HTML"}[fmt]- print(t("cli.session.save_ok", path=path, label=label))- # #76354 review F5: the worker thread also rebound the session ContextVar inside its own- # (copied) context, which the caller never sees — and get_session_env() prefers an already-bound- # ContextVar over os.environ. Rebind in the CALLER's context so post-compression- # tools/subprocesses on this thread resolve HERMES_SESSION_ID to the child id after an- # out-of-place rotation (idempotent when no rotation happened).- if self.session_id:- print(f" {t('cli.session.save_resume_hint', session_id=self.session_id)}")- except Exception as e:- print(t("cli.session.save_failed", error=e))+ _write_save(self.session_id, fmt, filename, lambda: render_session_for_save(session_data, fmt))def _publish_truncated_history(self, truncated: list, *, invalidate_prompt: bool) -> None:"""Install a rewound history and mirror it onto the agent (flush index reset so thediff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.pyindex e04c5d363de..41ab48187ab 100644--- a/tests/gateway/test_session_tui_ops.py+++ b/tests/gateway/test_session_tui_ops.py@@ -6,6 +6,7 @@ from pathlib import Pathimport pytest+from hermes_state import SessionDBfrom tests.gateway.test_session_busy_controls import owner, settledfrom tests.gateway.fixtures.local_recovery_probe import rpc, websocket@@ -137,6 +138,29 @@ def test_session_export_keeps_the_assistant_reply_and_refuses_a_client_path(tmp_asyncio.run(probe())+[email protected]("linux")+def test_session_export_json_restores_with_its_title_through_import_sessions(tmp_path):+ """CLI-19: the classic CLI's ``/save json`` is this export, so it must be the canonical snapshot:+ ``import_sessions`` restores the session with its title and messages."""+ with owner(tmp_path) as (home, _peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='rt', source='tui', toolsets=[]))['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='first', text='SAVE_ME')+ await settled(home)+ revision = (await rpc(ws, 'session.resume', session_id=sid))['result']['revision']+ renamed = await rpc(ws, 'session.mutate', session_id=sid, request_id='title', expected_revision=revision,+ operation='rename', payload={'title': 'Saved Title'})+ assert 'result' in renamed, renamed+ data = json.loads((await rpc(ws, 'session.export', session_id=sid, format='json'))['result']['content'])+ assert data['title'] == 'Saved Title' and all('active' in m for m in data['messages']), data+ with SessionDB(db_path=tmp_path / 'restored.db') as restored:+ assert restored.import_sessions([data])['ok']+ assert restored.get_session(data['id'])['title'] == 'Saved Title'+ assert 'SAVE_ME' in [m['content'] for m in restored.get_messages(data['id'])]+ asyncio.run(probe())+def _checkpoint(home, cwd, reason):"""A checkpoint in the owner profile's shared store (what the agent takes before a write)."""from hermes_constants import reset_hermes_home_override, set_hermes_home_overridediff --git a/tests/hermes_cli/test_gateway_cli_commands.py b/tests/hermes_cli/test_gateway_cli_commands.pyindex b3f5d7e5fe3..49cb200c3fa 100644--- a/tests/hermes_cli/test_gateway_cli_commands.py+++ b/tests/hermes_cli/test_gateway_cli_commands.py@@ -2,6 +2,7 @@CLI-8, CLI-17, CLI-21): ``/diff session`` (the gateway tools' checkpoint baseline), ``/reload``(the gateway's ``.env``) and ``/handoff`` (no gateway verb yet: refused, never silent). Driventhrough ``HermesCLI.process_command`` with a scripted gateway connection."""+from datetime import datetimefrom types import SimpleNamespaceimport pytest@@ -10,7 +11,7 @@ from cli import HermesCLIclass _Conn:- closed = False+ closed = final = Falsedef __init__(self, replies):self.replies = replies@@ -18,7 +19,10 @@ class _Conn:def call(self, method, **params):self.calls.append((method, params))- return self.replies.get(method, {})+ reply = self.replies.get(method, {})+ if isinstance(reply, Exception):+ raise reply+ return replydef _observed(name, arg):@@ -98,3 +102,58 @@ def test_handoff_is_refused_with_a_message_on_the_gateway(gateway_cli, capsys):assert cli.process_command("/handoff telegram") is True # the session staysassert "/handoff is not available on the shared gateway yet" in capsys.readouterr().outassert conn.calls == [] # a named refusal runs nothing: no command.observe (pre_command) either++++def _save_cli(conn, tmp_path, monkeypatch):+ """A gateway-backed CLI with one said line in its mirror, run from ``tmp_path/work``."""+ from hermes_cli.gateway_session_store import GatewaySessionStore+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id, cli.conversation_history = "local-s", [{"role": "user", "content": "in-memory only"}]+ cli.model, cli.session_start = "fake-model", datetime(2026, 10, 18)+ cli._session_db = GatewaySessionStore(conn)+ (tmp_path / "work").mkdir()+ monkeypatch.chdir(tmp_path / "work")+ return cli+++def test_save_writes_the_gateway_owners_export_on_this_machine(tmp_path, monkeypatch, capsys):+ """CLI-19: ``/save`` asks the owner (``session.export``) for its canonical export, never writes the+ in-memory fallback (no title, no metadata, no archived rows) that ``import_sessions`` can't restore.+ The CLI writes the content itself, so a remote owner's disk is never taken for this one."""+ from hermes_constants import get_hermes_home+ conn = _Conn({"session.export": {"format": "md", "filename": "hermes_session_s.md", "content": "# owner export"}})+ cli = _save_cli(conn, tmp_path, monkeypatch)+ work = tmp_path / "work"+ cli.save_conversation("/save markdown notes.md redact")+ assert conn.calls == [("session.export", {"session_id": "local-s", "format": "md", "redact": True})]+ assert (work / "notes.md").read_text(encoding="utf-8") == "# owner export"+ assert str(work / "notes.md") in capsys.readouterr().out+ cli.save_conversation("/save md") # no name: main's local folder and name, under this CLI's home+ [default] = (get_hermes_home() / "sessions" / "saved").glob("hermes_conversation_*.md")+ assert default.read_text(encoding="utf-8") == "# owner export" and str(default) in capsys.readouterr().out+ conn.replies["session.export"] = {} # an owner answer without content is reported, nothing written+ cli.save_conversation("/save json x.json")+ assert "Failed to save" in capsys.readouterr().out+ cli.conversation_history = [] # nothing said yet: nothing asked of the owner, nothing written+ cli.save_conversation("/save json")+ assert "No conversation to save" in capsys.readouterr().out and len(conn.calls) == 3+ assert [p.name for p in work.iterdir()] == ["notes.md"]+++def test_save_on_an_older_gateway_falls_back_only_for_a_plain_json_save(tmp_path, monkeypatch, capsys):+ """An owner without ``session.export`` (-32601): its ``session.save`` writes default-named, unredacted+ JSON on the gateway host, so only ``/save json`` uses it, reported as on the gateway host; a+ format, name or ``redact`` is refused with a message, never silently dropped."""+ from hermes_cli.gateway_client import GatewayRPCError+ conn = _Conn({"session.export": GatewayRPCError("unknown_method", code=-32601),+ "session.save": {"file": "/srv/gw/sessions/saved/hermes_conversation_x.json"}})+ cli = _save_cli(conn, tmp_path, monkeypatch)+ for cmd in ("/save md", "/save json mine.json", "/save json redact"):+ cli.save_conversation(cmd)+ assert "predates this CLI" in capsys.readouterr().out, cmd+ assert [m for m, _ in conn.calls] == ["session.export"] * 3+ cli.save_conversation("/save json")+ assert conn.calls[-1] == ("session.save", {"session_id": "local-s"})+ assert "saved on the gateway host: /srv/gw/sessions/saved/hermes_conversation_x.json" in capsys.readouterr().out+ assert not any((tmp_path / "work").iterdir())