Skip to content

The agent that grows with you

fix(gateway): -p <profile> stop/restart on a host-served profile refuses while its turns are live

Teknium76e8208d1991
diff --git a/gateway/run_active_work_verb.py b/gateway/run_active_work_verb.py
index 5ba939ad932..790857bd619 100644
--- a/gateway/run_active_work_verb.py
+++ b/gateway/run_active_work_verb.py
@@ -29,10 +29,25 @@ def _delegation_units(now: float) -> list[dict[str, Any]]:
return units
+def _profile_units(runner, profile: str, units: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """What an ``unserve-profile`` of *profile* stops (``stop_authority_work``): its chat turns (session
+ keys in its namespace) plus its authority's managed turns and cron runs. Delegations survive it."""
+ from gateway.session import _session_key_namespace
+
+ prefix = _session_key_namespace(profile) + ":"
+ mine = [u for u in units if u.get("kind") == "chat" and str(u.get("session") or "").startswith(prefix)]
+ home = (getattr(runner, "_served_profile_homes", None) or {}).get(profile)
+ registry = getattr(runner, "session_authorities", None)
+ authority = registry.for_home(home) if registry is not None and home is not None else None
+ managed = sum(not w.closed.is_set() for w in getattr(authority, "_managed_workers", {}).values())
+ crons = len(getattr(authority, "_cron_cancellations", None) or {})
+ return mine + [{"kind": "managed", "pid": os.getpid()}] * managed + [{"kind": "cron", "job_id": "?", "pid": os.getpid()}] * crons
+
+
def active_work_verb(runner, loop) -> Callable[[], dict[str, Any]]:
"""Handler for the control socket: runs on its executor thread, reads the runner on the loop."""
- def _handler() -> dict[str, Any]:
+ def _handler(params: dict[str, Any]) -> dict[str, Any]:
box: list[list] = []
done = threading.Event()
@@ -46,6 +61,10 @@ def active_work_verb(runner, loop) -> Callable[[], dict[str, Any]]:
done.wait(timeout=5.0)
units = list(box[0]) if box else []
units += _delegation_units(time.time())
+ profile = params.get("profile")
+ if isinstance(profile, str) and profile:
+ units = _profile_units(runner, profile, units)
+ return {"active_agents": len(units), "active_work": units, "pid": os.getpid(), "profile": profile}
return {"active_agents": runner._active_work_count(), "active_work": units, "pid": os.getpid()}
return _handler
diff --git a/hermes_cli/gateway_lifecycle_guards.py b/hermes_cli/gateway_lifecycle_guards.py
index df21d00c35c..4c6fe0b7eb5 100644
--- a/hermes_cli/gateway_lifecycle_guards.py
+++ b/hermes_cli/gateway_lifecycle_guards.py
@@ -36,15 +36,16 @@ def _live_work_from_state(home: Path) -> Optional[dict[str, Any]]:
"active_work": work if isinstance(work, list) else []}
-def live_work(home: Path) -> Optional[dict[str, Any]]:
+def live_work(home: Path, profile: Optional[str] = None) -> Optional[dict[str, Any]]:
"""What the gateway serving ``home`` is running now: ``{"active_agents", "active_work"}``, or None
- when no gateway answers. The control socket answers live; the state file covers older gateways."""
+ when no gateway answers. The control socket answers live; the state file covers older gateways.
+ ``profile`` narrows the answer to one served profile's work (the state file cannot, so it is skipped)."""
from gateway.control_socket import query_gateway_control
- answer = query_gateway_control(home, "active-work")
+ answer = query_gateway_control(home, "active-work", params={"profile": profile} if profile else None)
if isinstance(answer, dict) and isinstance(answer.get("active_work"), list):
return answer
- return _live_work_from_state(home)
+ return None if profile else _live_work_from_state(home)
def _candidate_homes(system: bool = False) -> list[Path]:
@@ -66,12 +67,13 @@ def _candidate_homes(system: bool = False) -> list[Path]:
return homes
-def refusal_lines(verb: str, homes: list[Path], *, flag_hint: str = f"hermes gateway {{verb}} {INTERRUPT_FLAG}") -> list[str]:
+def refusal_lines(verb: str, homes: list[Path], *, flag_hint: str = f"hermes gateway {{verb}} {INTERRUPT_FLAG}",
+ profile: Optional[str] = None) -> list[str]:
"""Refusal text for ``verb`` while the first answering gateway among ``homes`` has live work, else []."""
from hermes_cli.update_cmd_drain_report import describe_active_work_unit
for home in homes:
- work = live_work(home)
+ work = live_work(home, profile)
if work is not None:
break
else:
@@ -89,9 +91,15 @@ def refusal_lines(verb: str, homes: list[Path], *, flag_hint: str = f"hermes gat
return lines
-def refuse_while_sessions_live(verb: str, args) -> None:
- """Exit 1 naming the live work unless ``--interrupt`` was passed; with it, say what is interrupted."""
- lines = refusal_lines(verb, _candidate_homes(getattr(args, "system", False)))
+def refuse_while_sessions_live(verb: str, args, *, host_home: Optional[Path] = None, profile: Optional[str] = None) -> None:
+ """Exit 1 naming the live work unless ``--interrupt`` was passed; with it, say what is interrupted.
+ ``host_home``/``profile``: a served profile's stop/restart unserves only that profile in the host,
+ so only its work counts."""
+ if profile:
+ lines = refusal_lines(verb, [Path(host_home)], profile=profile,
+ flag_hint=f"hermes -p {profile} gateway {{verb}} {INTERRUPT_FLAG}")
+ else:
+ lines = refusal_lines(verb, _candidate_homes(getattr(args, "system", False)))
if not lines:
return
from hermes_cli.gateway import print_error, print_warning
diff --git a/hermes_cli/gateway_profile_lifecycle.py b/hermes_cli/gateway_profile_lifecycle.py
index 491d848ca41..140f4332d0a 100644
--- a/hermes_cli/gateway_profile_lifecycle.py
+++ b/hermes_cli/gateway_profile_lifecycle.py
@@ -88,6 +88,9 @@ def profile_lifecycle(command: str, args) -> bool:
if owner is None and not gw.named_profile_served_by_running_multiplexer():
return False
host_home = owner.home if owner is not None else get_default_hermes_root()
+ # Unserving stops this profile's executing turns: the live-work policy applies before the teardown.
+ from hermes_cli.gateway_lifecycle_guards import refuse_while_sessions_live
+ refuse_while_sessions_live(command, args, host_home=host_home, profile=name)
if command == "stop":
# Persist intent BEFORE teardown: the periodic rescan must not re-add this profile.
marker.touch()
diff --git a/tests/hermes_cli/test_gateway_lifecycle_guards.py b/tests/hermes_cli/test_gateway_lifecycle_guards.py
index 4c18d44b447..0e0a24cd22e 100644
--- a/tests/hermes_cli/test_gateway_lifecycle_guards.py
+++ b/tests/hermes_cli/test_gateway_lifecycle_guards.py
@@ -224,3 +224,58 @@ def test_sudo_system_stop_checks_the_units_home_not_roots(tmp_path, monkeypatch,
assert "chat turn agent:main:telegram:dm:7" in capsys.readouterr().out
assert "HERMES_HOME" not in os.environ # the check never adopted the unit's home
+
[email protected]("verb", ["stop", "restart"])
+def test_host_served_profile_refuses_before_unserving_its_live_turns(tmp_path, monkeypatch, capsys, verb):
+ """``hermes -p coder gateway stop|restart`` on a profile the host serves unserves it in the host,
+ which Stops its executing turns: the live-work policy applies first, scoped to that profile."""
+ from gateway import control_socket
+ from hermes_cli import gateway_profile_lifecycle as gpl
+ profile_home, host_home = tmp_path / "profiles" / "coder", tmp_path / "root"
+ profile_home.mkdir(parents=True)
+ monkeypatch.setattr(gw, "_current_profile_name", lambda: "coder")
+ monkeypatch.setattr(gpl, "get_hermes_home", lambda: profile_home)
+ monkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [])
+ monkeypatch.setattr(gw, "_served_by_another_host_gateway", lambda: SimpleNamespace(home=host_home))
+ asked: list = []
+ coder_work = {"active_agents": 1, "active_work": [_WORK["active_work"][0] | {"session": "agent:coder:telegram:dm:7"}]}
+ monkeypatch.setattr(control_socket, "query_gateway_control",
+ lambda home, verb, params=None, **kw: asked.append((home, params)) or (
+ coder_work if (params or {}).get("profile") == "coder" else _WORK))
+ requests: list = []
+ monkeypatch.setattr(control_socket, "request_unserve_profile",
+ lambda home, name: requests.append(("unserve", name)) or {"unserved": name})
+ monkeypatch.setattr(control_socket, "request_serve_profile_hot",
+ lambda home, name: requests.append(("serve", name)) or {"served": name})
+ command = getattr(gw, f"_cmd_{verb}")
+
+ with pytest.raises(SystemExit) as exc:
+ command(SimpleNamespace(all=False, system=False, force=False, interrupt=False))
+
+ out = capsys.readouterr().out
+ assert exc.value.code == 1 and requests == []
+ assert asked == [(host_home, {"profile": "coder"})]
+ assert "1 live session(s)" in out and "agent:coder:telegram:dm:7" in out
+ assert f"hermes -p coder gateway {verb} --interrupt" in out
+ assert not (profile_home / "gateway.parked").exists()
+
+ command(SimpleNamespace(all=False, system=False, force=False, interrupt=True))
+ assert requests[0] == ("unserve", "coder")
+
+
+def test_active_work_verb_scoped_to_a_profile_names_only_its_turns(monkeypatch):
+ """The host's ``active-work`` verb with ``{"profile": "coder"}`` answers only what unserving coder stops."""
+ from gateway.run_active_work_verb import active_work_verb
+ from tools import async_delegation
+ monkeypatch.setattr(async_delegation, "list_async_delegations", list)
+ units = [{"kind": "chat", "session": "agent:coder:telegram:dm:7", "pid": 1},
+ {"kind": "chat", "session": "agent:main:telegram:dm:8", "pid": 1}]
+ runner = SimpleNamespace(_describe_active_work=lambda: units, _active_work_count=lambda: 2,
+ _served_profile_homes={}, session_authorities=None)
+ loop = SimpleNamespace(call_soon_threadsafe=lambda fn: fn())
+ handler = active_work_verb(runner, loop)
+
+ assert handler({})["active_agents"] == 2
+ scoped = handler({"profile": "coder"})
+ assert scoped["active_agents"] == 1 and [u["session"] for u in scoped["active_work"]] == ["agent:coder:telegram:dm:7"]
+