The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /goal, /subgoal, /loop, /heartbeat state and judging run in the gateway
Tekniumb52ee9c8aa8e
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex b189e7eb2bc..4a290374a4c 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1978,7 +1978,7 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):# ---- /goal, /loop, /subgoal -----------------------------------------------------------def _handle_goal_command(self, cmd: str) -> None:- from hermes_cli.goal_command import dispatch_goal_command+ from hermes_cli.gateway_automation import dispatch_goal_command # /goal draft drafts on the gatewayfrom hermes_cli.goals import last_user_message_contentmgr = self._session_manager(self._get_goal_manager, _t("goal.label"))@@ -2017,8 +2017,8 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):_cp(f" {line}")if result.get("created"):with suppress(Exception):- from hermes_cli.loops import goal_blocks_loop_tick- if goal_blocks_loop_tick(mgr.session_id):+ from hermes_cli.cli_loops_mixin import _goal_blocks_loop_tick+ if _goal_blocks_loop_tick(mgr):_cp(_dim_line(_t("loop.goal_defers_note")))def _handle_subgoal_command(self, cmd: str) -> None:diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.pyindex 7f536ad3e2f..6a2da8ec63e 100644--- a/hermes_cli/cli_loops_mixin.py+++ b/hermes_cli/cli_loops_mixin.py@@ -64,6 +64,15 @@ def _print_decision_message(decision: dict) -> bool:return bool(msg)+def _goal_blocks_loop_tick(mgr) -> bool:+ """``loops.goal_blocks_loop_tick`` for this loop's session: asked of the gateway when the manager+ is the gateway's (it reads the goal row and its barrier where they live)."""+ if hasattr(mgr, "goal_blocks_tick"):+ return mgr.goal_blocks_tick()+ from hermes_cli.loops import goal_blocks_loop_tick+ return goal_blocks_loop_tick(mgr.session_id)++class CLILoopsMixin:"""Simple slash-command wrappers plus goal/heartbeat/loop manager hooks for the interactive CLI"""@@ -498,35 +507,64 @@ class CLILoopsMixin:setattr(self, attr, mgr)return mgr+ def _automation_connection(self):+ """``(gateway, connection)``: on a gateway session store the managers are the gateway's+ (``hermes_cli.gateway_automation``), and none exists until the gateway session is open, so this+ process never opens state.db read-write nor calls the goal judge. Off the gateway (tests, the+ TUI slash worker's shadow CLI) main's in-process managers apply."""+ from hermes_cli.gateway_session_store import GatewaySessionStore+ store = getattr(self, "_session_db", None)+ if not isinstance(store, GatewaySessionStore):+ return False, None+ return True, store.connection if getattr(self, "_gateway_session_open", False) else None++ def _automation_manager(self, attr, label, local, remote):+ gateway, connection = self._automation_connection()+ if gateway and connection is None:+ return None+ return self._session_bound_manager(+ attr, label, (lambda: lambda sid: remote(sid, connection)) if gateway else local)+def _get_goal_manager(self):"""GoalManager bound to the current session_id (see ``_session_bound_manager``)."""+ def max_turns():+ from hermes_cli.config import load_config+ try:+ goals_cfg = (load_config() or {}).get("goals") or {}+ return int(goals_cfg.get("max_turns", 20) or 20)+ except Exception: # health: allow BLE001 -- main's fallback: an unreadable goals config is the 20-turn default+ return 20+def load():from hermes_cli.goals import GoalManager- from hermes_cli.config import load_config+ return lambda sid: GoalManager(session_id=sid, default_max_turns=max_turns())- def make(sid):- try:- goals_cfg = (load_config() or {}).get("goals") or {}- max_turns = int(goals_cfg.get("max_turns", 20) or 20)- except Exception:- max_turns = 20- return GoalManager(session_id=sid, default_max_turns=max_turns)- return make- return self._session_bound_manager("_goal_manager", "goal manager", load)+ def remote(sid, connection):+ from hermes_cli.gateway_automation import GatewayGoalManager+ return GatewayGoalManager(sid, connection)+ return self._automation_manager("_goal_manager", "goal manager", load, remote)def _get_heartbeat_manager(self):"""HeartbeatManager bound to the current session_id (see ``_session_bound_manager``)."""def load():from hermes_cli.heartbeat import HeartbeatManagerreturn lambda sid: HeartbeatManager(session_id=sid)- return self._session_bound_manager("_heartbeat_manager", "heartbeat manager", load)++ def remote(sid, connection):+ from hermes_cli.gateway_automation import GatewayHeartbeatManager+ return GatewayHeartbeatManager(sid, connection)+ return self._automation_manager("_heartbeat_manager", "heartbeat manager", load, remote)def _get_loop_manager(self):"""LoopManager bound to the current session_id (see ``_session_bound_manager``)."""def load():from hermes_cli.loops import LoopManagerreturn lambda sid: LoopManager(session_id=sid)- return self._session_bound_manager("_loop_manager", "loop manager", load)++ def remote(sid, connection):+ from hermes_cli.gateway_automation import GatewayLoopManager+ return GatewayLoopManager(sid, connection)+ return self._automation_manager("_loop_manager", "loop manager", load, remote)def _start_heartbeat_watchdog(self):"""Start the idle-poll daemon that injects a due heartbeat prompt into@@ -614,8 +652,7 @@ class CLILoopsMixin:except Exception:returntry:- from hermes_cli.loops import goal_blocks_loop_tick- if goal_blocks_loop_tick(mgr.session_id):+ if _goal_blocks_loop_tick(mgr):returnexcept Exception:passdiff --git a/hermes_cli/gateway_automation.py b/hermes_cli/gateway_automation.pynew file mode 100644index 00000000000..49e561c2f36--- /dev/null+++ b/hermes_cli/gateway_automation.py@@ -0,0 +1,277 @@+"""The classic CLI's /goal, /subgoal, /loop and /heartbeat managers, backed by the gateway session.++Main's ``HermesCLI`` built ``GoalManager`` / ``LoopManager`` / ``HeartbeatManager`` in-process: each+mutation wrote ``state_meta`` through a read-write SessionDB and ``evaluate_after_turn`` called the goal+judge model from the CLI pid. Rewired, the gateway is the single writer and runs every model call, so+these are thin proxies (the GatewayAgent / GatewaySessionStore seam): every mutation and judgement is+one ``session.automation`` call, and the persisted state the gateway returns is cached here so the+status bar, the dock and main's read-only helpers (``status_line``, ``is_due``, ``render_gates``…) keep+running main's own code, unchanged, against the same state object.+"""+from __future__ import annotations++import logging++from hermes_cli.gateway_client import GatewayClientError++logger = logging.getLogger(__name__)++_ERRORS = {"RuntimeError": RuntimeError, "ValueError": ValueError, "IndexError": IndexError}+++def _decode(value):+ if isinstance(value, dict):+ if set(value) == {"__state__"}:+ return value["__state__"]+ if set(value) == {"__gate__"}:+ from hermes_cli.goals import GoalGate+ return GoalGate.from_dict(value["__gate__"])+ return {k: _decode(v) for k, v in value.items()}+ if isinstance(value, list):+ return [_decode(v) for v in value]+ return value+++class _Remote:+ """Shared plumbing: ``self._state`` mirrors the gateway's row; ``_rpc`` runs one call there."""++ kind = ""+ _state_cls: type = type(None)++ def __init__(self, session_id, connection, *, load=True):+ self.session_id = session_id+ self._connection = connection+ self._state = None+ if load:+ self.refresh()++ @property+ def state(self):+ return self._state++ def _adopt(self, raw):+ state = self._state_cls.from_json(raw) if raw else None+ self._state = None if state is None or state.status == "cleared" else state+ return self._state++ def _rpc(self, call, *args, **kwargs):+ try:+ reply = self._connection.call("session.automation", session_id=self.session_id, kind=self.kind,+ call=call, args=list(args), kwargs=kwargs)+ except GatewayClientError as exc:+ # Main's managers swallowed a dropped write (debug log, no crash); the REPL stays up.+ logger.debug("session.automation %s.%s failed: %s", self.kind, call, exc)+ return None+ self._adopt(reply.get("state"))+ error = reply.get("error")+ if error:+ raise _ERRORS.get(error.get("type"), RuntimeError)(error.get("message") or "")+ value = _decode(reply.get("value"))+ return self._state if isinstance(value, str) and value == reply.get("state") and value else value++ def refresh(self):+ self._rpc("state")+++class GatewayGoalManager(_Remote):+ """``hermes_cli.goals.GoalManager`` over the gateway (same method names and returns)."""++ kind = "goal"++ def __init__(self, session_id, connection, *, default_max_turns=None, load=True):+ from hermes_cli.goals import GoalState+ self._state_cls = GoalState+ self.default_max_turns = default_max_turns+ super().__init__(session_id, connection, load=load)++ # Main's pure reads, on the mirrored state (``GoalManager`` methods bound to this object).+ from hermes_cli.goals import GoalManager as _Local+ is_active = _Local.is_active+ has_goal = _Local.has_goal+ has_contract = _Local.has_contract+ status_line = _Local.status_line+ render_subgoals = _Local.render_subgoals+ render_gates = _Local.render_gates+ render_contract = _Local.render_contract+ next_continuation_prompt = _Local.next_continuation_prompt+ del _Local++ def set(self, goal, *, max_turns=None, contract=None):+ kwargs = {"max_turns": max_turns} if max_turns is not None else {}+ if contract is not None:+ kwargs["contract"] = contract.to_dict()+ return self._rpc("set", goal, **kwargs)++ def pause(self, reason="user-paused"):+ return self._rpc("pause", reason=reason)++ def resume(self, *, reset_budget=True):+ return self._rpc("resume", reset_budget=reset_budget)++ def clear(self):+ self._rpc("clear")++ def mark_done(self, reason):+ self._rpc("mark_done", reason)++ def add_subgoal(self, text):+ return self._rpc("add_subgoal", text)++ def remove_subgoal(self, index_1based):+ return self._rpc("remove_subgoal", int(index_1based))++ def clear_subgoals(self):+ return self._rpc("clear_subgoals")++ def add_gate(self, command, *, timeout_seconds=None, max_retries=None):+ kwargs = {k: v for k, v in (("timeout_seconds", timeout_seconds), ("max_retries", max_retries)) if v}+ return self._rpc("add_gate", command, **kwargs)++ def remove_gate(self, index_1based):+ return self._rpc("remove_gate", int(index_1based))++ def clear_gates(self):+ return self._rpc("clear_gates")++ def wait_on(self, pid, reason=""):+ return self._rpc("wait_on", int(pid), reason=reason)++ def wait_on_session(self, session_id, reason=""):+ return self._rpc("wait_on_session", session_id, reason=reason)++ def wait_for_seconds(self, seconds, reason="", *, on_delegations=0):+ return self._rpc("wait_for_seconds", int(seconds), reason=reason, on_delegations=on_delegations)++ def stop_waiting(self):+ return bool(self._rpc("stop_waiting"))++ def is_waiting(self):+ """Barrier check (and lazy clear) where the barrier lives: the pid / process session is the+ gateway's. A state with no barrier answers locally, so the idle poll costs no round trip."""+ s = self._state+ if s is None or (s.waiting_on_pid is None and s.waiting_on_session is None and not s.waiting_until):+ return False+ return bool(self._rpc("is_waiting"))++ def command(self, arg, last_user_message=None):+ """The whole ``/goal <arg>`` run by the gateway (``/goal draft``: its contract drafter is a model call)."""+ from hermes_cli.goal_command import GoalCommandResult+ result = self._rpc("command", arg, last_user_message)+ if not isinstance(result, dict):+ return GoalCommandResult("Goal unavailable: the gateway did not answer.", error=True)+ return GoalCommandResult(**{k: v for k, v in result.items() if k in GoalCommandResult.__dataclass_fields__})++ def evaluate_after_turn(self, last_response, *, user_initiated=True, background_processes=None,+ active_delegations=0):+ """The judge runs in the gateway (``auxiliary.goal_judge``), with the gateway's background+ processes and delegations; the decision dict is main's."""+ decision = self._rpc("evaluate_after_turn", last_response or "")+ if not isinstance(decision, dict):+ return {"status": None, "should_continue": False, "continuation_prompt": None,+ "verdict": "inactive", "reason": "gateway unavailable", "message": ""}+ return decision+++class GatewayLoopManager(_Remote):+ """``hermes_cli.loops.LoopManager`` over the gateway."""++ kind = "loop"++ def __init__(self, session_id, connection, *, load=True):+ from hermes_cli.loops import LoopState+ self._state_cls = LoopState+ super().__init__(session_id, connection, load=load)++ from hermes_cli.loops import LoopManager as _Local+ is_active = _Local.is_active+ has_loop = _Local.has_loop+ status_line = _Local.status_line+ is_due = _Local.is_due+ del _Local++ def set(self, prompt, *, interval_seconds=None, times=0, until="", route=None):+ return self._rpc("set", prompt, interval_seconds=interval_seconds, times=times, until=until)++ def pause(self, reason="user-paused"):+ return self._rpc("pause", reason=reason)++ def resume(self):+ return self._rpc("resume")++ def clear(self):+ return bool(self._rpc("clear"))++ def fire_tick(self):+ return self._rpc("fire_tick")++ def abandon_tick(self):+ self._rpc("abandon_tick")++ def complete_tick(self, last_response):+ decision = self._rpc("complete_tick", last_response or "")+ return decision if isinstance(decision, dict) else {"status": None, "stopped": False,+ "reason": "gateway unavailable", "message": ""}++ def goal_blocks_tick(self):+ return bool(self._rpc("goal_blocks_tick"))+++class GatewayHeartbeatManager(_Remote):+ """``hermes_cli.heartbeat.HeartbeatManager`` over the gateway."""++ kind = "heartbeat"++ def __init__(self, session_id, connection, *, load=True):+ from hermes_cli.heartbeat import HeartbeatState+ self._state_cls = HeartbeatState+ super().__init__(session_id, connection, load=load)++ from hermes_cli.heartbeat import HeartbeatManager as _Local+ has_heartbeat = _Local.has_heartbeat+ is_active = _Local.is_active+ status_line = _Local.status_line+ del _Local++ def set(self, prompt, interval_seconds):+ return self._rpc("set", prompt, int(interval_seconds))++ def pause(self):+ return self._rpc("pause")++ def resume(self):+ return self._rpc("resume")++ def clear(self):+ return bool(self._rpc("clear"))++ def due_prompt(self, now=None):+ s = self._state+ if s is None or not s.is_due(now):+ return None # main's cheap local check first: the idle poll costs no round trip+ return self._rpc("due_prompt")++ def abandon_fire(self):+ return bool(self._rpc("abandon_fire"))+++def dispatch_goal_command(mgr, arg, *, authorize_gate, last_user_message=None, progress=None):+ """``goal_command.dispatch_goal_command`` for the classic CLI: on a gateway manager ``/goal draft``+ (its contract drafter is an auxiliary-model call) runs whole on the gateway; every other form is+ main's dispatcher over the proxy, so its output strings stay main's."""+ from hermes_cli import goal_command+ if isinstance(mgr, GatewayGoalManager) and (arg or "").split(None, 1)[:1] == ["draft"]:+ if progress is not None:+ progress("Drafting completion contract…")+ return mgr.command(arg, last_user_message)+ return goal_command.dispatch_goal_command(mgr, arg, authorize_gate=authorize_gate,+ last_user_message=last_user_message, progress=progress)+++def gateway_connection(cli):+ """The CLI's gateway connection when its session store is the gateway's, else None (main's local+ managers: tests and the TUI slash worker's shadow CLI)."""+ from hermes_cli.gateway_session_store import GatewaySessionStore+ store = getattr(cli, "_session_db", None)+ if isinstance(store, GatewaySessionStore) and getattr(cli, "_gateway_session_open", False):+ return store.connection+ return Nonediff --git a/tests/hermes_cli/test_gateway_automation.py b/tests/hermes_cli/test_gateway_automation.pynew file mode 100644index 00000000000..5103bfd048a--- /dev/null+++ b/tests/hermes_cli/test_gateway_automation.py@@ -0,0 +1,95 @@+"""The classic CLI's /goal, /loop, /heartbeat managers on a gateway session are proxies over+``session.automation``: no local GoalManager (so no read-write state.db in the CLI pid, no judge model+call), main's read helpers run on the mirrored state, and manager refusals keep main's exceptions."""+import json+from types import SimpleNamespace++import pytest+++class _Conn:+ """A fake gateway: runs every call against main's in-process managers on a private store."""++ def __init__(self):+ self.calls = []+ self.closed = False++ def call(self, method, **params):+ from gateway.session_viewer_automation import invoke+ self.calls.append((params['kind'], params['call']))+ return invoke(SimpleNamespace(), params['kind'], params['session_id'], params['call'],+ params['args'], params['kwargs'])+++def cli(tmp_path, monkeypatch):+ from hermes_cli import goals+ from hermes_cli.gateway_session_store import GatewaySessionStore+ from hermes_state import SessionDB+ db = SessionDB(db_path=tmp_path / 'owner.db')+ monkeypatch.setattr(goals, '_get_session_db', lambda: db) # the "gateway's" store+ conn = _Conn()+ store = GatewaySessionStore.__new__(GatewaySessionStore)+ store.connection = conn+ from hermes_cli.cli_loops_mixin import CLILoopsMixin+ obj = CLILoopsMixin.__new__(CLILoopsMixin)+ obj._session_db, obj._gateway_session_open, obj.session_id = store, True, 'sid-1'+ yield SimpleNamespace(cli=obj, conn=conn, db=db)+ db.close()+++def test_goal_manager_is_the_gateways(cli):+ mgr = cli.cli._get_goal_manager()+ assert type(mgr).__name__ == 'GatewayGoalManager'+ assert cli.conn.calls == [('goal', 'state')] # loaded from the gateway, not this process's store+ state = mgr.set('ship it')+ assert state.goal == 'ship it' and mgr.is_active()+ assert mgr.status_line() == '⊙ Goal (active, 0/20 turns): ship it'+ assert json.loads(cli.db.get_meta('goal:sid-1'))['goal'] == 'ship it'+ with pytest.raises(IndexError, match='index out of range'):+ mgr.remove_subgoal(4)+ assert cli.cli._get_goal_manager() is mgr # cached per session id, like main+++def test_no_manager_before_the_gateway_session_is_open(cli):+ cli.cli._gateway_session_open = False+ assert cli.cli._get_goal_manager() is None and cli.conn.calls == []+++def test_judge_decision_comes_from_the_gateway(cli, monkeypatch):+ from hermes_cli import goals+ monkeypatch.setattr(goals, 'judge_goal', lambda *a, **k: ('done', 'the report is written', False, None, False))+ mgr = cli.cli._get_goal_manager()+ mgr.set('write the report')+ decision = mgr.evaluate_after_turn('the report is written', user_initiated=True)+ assert decision['message'] == '✓ Goal achieved: the report is written'+ assert ('goal', 'evaluate_after_turn') in cli.conn.calls+ assert mgr.state.status == 'done'+++def test_idle_polls_cost_no_round_trip(cli):+ hb = cli.cli._get_heartbeat_manager()+ loop = cli.cli._get_loop_manager()+ goal = cli.cli._get_goal_manager()+ before = len(cli.conn.calls)+ assert hb.due_prompt() is None and not loop.is_due() and goal.is_waiting() is False+ assert len(cli.conn.calls) == before+ hb.set('pulse', 60)+ assert hb.is_active() and hb.status_line().startswith('♥ Heartbeat (every 1m')+ loop.set('check', interval_seconds=60, times=1)+ assert loop.is_due() and loop.fire_tick().startswith('[/loop wakeup #1')+ assert loop.complete_tick('done')['message'] == '✓ Loop finished — ran 1/1 times.'+++def test_goal_draft_drafts_on_the_gateway(cli, monkeypatch):+ from hermes_cli import goals+ from hermes_cli.gateway_automation import dispatch_goal_command+ drafted = []+ monkeypatch.setattr(goals, 'draft_contract', lambda objective, **k: drafted.append(objective) or None)+ mgr = cli.cli._get_goal_manager()+ lines = []+ result = dispatch_goal_command(mgr, 'draft ship the API', authorize_gate=lambda: None, progress=lines.append)+ assert drafted == ['ship the API'] and ('goal', 'command') in cli.conn.calls+ assert lines == ['Drafting completion contract…']+ assert result.output.startswith('⊙ Goal set (20-turn budget): ship the API') and result.kickoff+ assert mgr.state.goal == 'ship the API'