Skip to content

The agent that grows with you

fix(cli): hand the CLI lease over while the snapshot rejoin re-imports a row

kshitijk4poore9f3ef7ad54b
diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.py
index 65b202d9f19..6ffa60589bd 100644
--- a/hermes_cli/cli_init_mixin.py
+++ b/hermes_cli/cli_init_mixin.py
@@ -5,6 +5,7 @@ Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO.
from __future__ import annotations
+from contextlib import contextmanager
import logging
import os
import queue
@@ -87,6 +88,28 @@ def _record_shell_hook_consent():
logger.warning("shell-hook consent check failed", exc_info=True)
+@contextmanager
+def lease_handed_over(cli, held):
+ """Run a gateway attach without this CLI's own active-session lease, then re-claim it.
+
+ A row the gateway has not imported yet (a legacy / in-process session) is imported under the
+ active-session registry lock, which refuses (``runtime_coordination_required``) while ANY live
+ lease holds the id, including this process's own. The block may move ``cli.session_id`` to the
+ id the gateway returned: the lease is re-claimed for that id (main's exclusivity is kept), or
+ for the unchanged id when the block raises."""
+ if not held:
+ yield
+ return
+ cli._release_active_session()
+ try:
+ yield
+ except BaseException:
+ cli._claim_active_session("cli", stderr=True)
+ raise
+ if not cli._claim_active_session("cli", stderr=True):
+ raise RuntimeError("session_already_owned")
+
+
class CLIInitMixin:
"""HermesCLI constructor phases: display options, model/provider routing, turn limits, toolsets, checkpoints, prompt/reasoning, runtime state, session store and UI state."""
@@ -434,26 +457,19 @@ class CLIInitMixin:
if getattr(self, "_gateway_session_open", False) or not isinstance(store, GatewaySessionStore):
return
launch = _gateway_launch(self)
- # A resumed row this gateway has not imported yet (a legacy / in-process session) is imported
- # under the active-session registry lock, which refuses while ANY live lease holds the id —
- # including this process's own, claimed before the first turn. Hand the slot over around the
- # attach, then re-claim it for the id the gateway returned (main's exclusivity is kept).
held = getattr(self, "_resumed", False) and getattr(self, "_active_session_lease", None) is not None
_record_shell_hook_consent()
- if held:
- self._release_active_session()
- sid = store.open_session(self, launch)
- self._gateway_session_open = True
- from hermes_cli import gateway_plugin_commands, tools_config
- tools_config._gateway_plugin_toolsets = lambda: gateway_plugin_commands.toolsets(self)
- _adopt_gateway_toolsets(self, store)
- from hermes_cli.gateway_tools import bind_session
- bind_session(self, store.connection) # the session's processes, before _init_agent's chat proxy
- if sid and sid != self.session_id:
- self.session_id = sid
- getattr(self, "_write_terminal_breadcrumb", lambda: None)()
- if held and not self._claim_active_session("cli", stderr=True):
- raise RuntimeError("session_already_owned")
+ with lease_handed_over(self, held):
+ sid = store.open_session(self, launch)
+ self._gateway_session_open = True
+ from hermes_cli import gateway_plugin_commands, tools_config
+ tools_config._gateway_plugin_toolsets = lambda: gateway_plugin_commands.toolsets(self)
+ _adopt_gateway_toolsets(self, store)
+ from hermes_cli.gateway_tools import bind_session
+ bind_session(self, store.connection) # the session's processes, before _init_agent's chat proxy
+ if sid and sid != self.session_id:
+ self.session_id = sid
+ getattr(self, "_write_terminal_breadcrumb", lambda: None)()
def _new_session_id(self, now, *, branch_of=None, title=None):
"""The id main mints for /new (``new_session_id``) and /branch (``mint_session_id``). On a gateway
diff --git a/hermes_cli/cli_snapshot.py b/hermes_cli/cli_snapshot.py
index 49122e98160..691f58f07f0 100644
--- a/hermes_cli/cli_snapshot.py
+++ b/hermes_cli/cli_snapshot.py
@@ -128,29 +128,25 @@ def _restore_gateway_snapshot(cli, store, snap_id):
def _rejoin_cli(cli, store):
- from hermes_cli.cli_init_mixin import _ROUTE_FLAGS, _gateway_launch
+ from hermes_cli.cli_init_mixin import _ROUTE_FLAGS, _gateway_launch, lease_handed_over
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")
+ # A snapshot older than the gateway's import of a legacy row makes this attach import it again.
+ with lease_handed_over(cli, getattr(cli, "_active_session_lease", None) is not 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
+ cli.session_id = snapshot["stored_session_id"]
+ 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)
getattr(cli, "_write_terminal_breadcrumb", lambda: None)()
diff --git a/tests/hermes_cli/test_gateway_snapshot_restore_live.py b/tests/hermes_cli/test_gateway_snapshot_restore_live.py
index 2bbde1a5c1b..14c40f7870c 100644
--- a/tests/hermes_cli/test_gateway_snapshot_restore_live.py
+++ b/tests/hermes_cli/test_gateway_snapshot_restore_live.py
@@ -119,18 +119,38 @@ def _default_profile_state(home):
db.execute("SELECT session_id,role,content FROM messages ORDER BY id").fetchall())
+def _legacy_row(home):
+ """A pre-authority CLI row the gateway has not imported yet, as the old in-process CLI wrote it."""
+ from hermes_state import SessionDB
+ db = SessionDB(home / "state.db")
+ try:
+ db.create_session("legacy-cli", source="cli", model="fixture")
+ db.append_message("legacy-cli", role="user", content="BEFORE_SNAPSHOT")
+ db.append_message("legacy-cli", role="assistant", content="BEFORE_SNAPSHOT answer")
+ db.end_session("legacy-cli", "cli_exit")
+ finally:
+ db.close()
+ return "legacy-cli"
+
+
@pytest.mark.platforms("posix") # The fixture exercises the POSIX default/named profile layout.
[email protected]("multiplex, retained", [(False, True), (True, False)],
- ids=["standalone-resume-restored", "satellite-create-missing"])
-def test_snapshot_restore_rejoins_the_restored_authority(local_gateway, multiplex, retained, capsys):
[email protected]("multiplex, mode", [(False, "retained"), (True, "missing"), (False, "legacy-leased")],
+ ids=["standalone-resume-restored", "satellite-create-missing", "legacy-reimport-leased"])
+def test_snapshot_restore_rejoins_the_restored_authority(local_gateway, multiplex, mode, capsys):
+ from cli import HermesCLI
+ from types import MethodType
home = local_gateway(multiplex)
+ legacy = _legacy_row(home) if mode == "legacy-leased" else None
+ # A legacy snapshot predates the gateway's import, so the rejoin must import the row again.
+ snapshot = create_quick_snapshot(hermes_home=home) if legacy else None
connection = GatewayConnection.shared()
store = GatewaySessionStore(connection)
- sid = store.create({"toolsets": []})
- _turn(store, sid, "BEFORE_SNAPSHOT")
- snapshot = create_quick_snapshot(hermes_home=home)
+ sid = store.attach(legacy)["stored_session_id"] if legacy else store.create({"toolsets": []})
+ if not legacy:
+ _turn(store, sid, "BEFORE_SNAPSHOT")
+ snapshot = create_quick_snapshot(hermes_home=home)
assert snapshot
- if not retained:
+ if mode == "missing":
store.end_session(sid)
sid = store.create({"toolsets": []})
_turn(store, sid, "AFTER_SNAPSHOT")
@@ -146,15 +166,24 @@ def test_snapshot_restore_rejoins_the_restored_authority(local_gateway, multiple
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,
+ cli = SimpleNamespace(_session_db=store, _gateway_session_open=True, session_id=sid, config={},
conversation_history=[{"role": "user", "content": "AFTER_SNAPSHOT"}],
- agent=object(), model="fixture")
-
- CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
+ agent=object(), model="fixture", _active_session_lease=None)
+ for name in ("_claim_active_session", "_release_active_session"):
+ setattr(cli, name, MethodType(getattr(HermesCLI, name), cli))
+ # The interactive CLI holds its real active-session lease for the whole chat.
+ assert cli._claim_active_session("cli", stderr=True)
+ retained = mode != "missing"
+ try:
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", snapshot])
- out = capsys.readouterr().out
- assert connection.final, out
- assert "Restored state from" in out and "failed" not in out and "not served again" not in out, out
+ out = capsys.readouterr().out
+ assert connection.final, out
+ assert "Restored state from" in out and "failed" not in out and "not served again" not in out, out
+ assert cli._active_session_lease is not None
+ assert cli._active_session_lease.session_id == cli.session_id
+ finally:
+ cli._release_active_session()
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