The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernetcbb9660c2cc6
diff --cc gateway/platforms/tcp_site.pyindex 6be1aa63b20,6be1aa63b20..77c9f698500--- a/gateway/platforms/tcp_site.py+++ b/gateway/platforms/tcp_site.py@@@ -1,14 -1,14 +1,17 @@@"""Bind an aiohttp ``TCPSite`` for the HTTP-serving adapters (webhook, api_server): exclusive on macOS,yet able to rebind over a lingering TIME_WAIT socket right after a gateway restart."""++from __future__ import annotations++import asyncioimport errnoimport loggingimport socketimport sys--from typing import Optional++from typing import TYPE_CHECKING, Optional--from aiohttp import web++if TYPE_CHECKING:++ from aiohttp import webfrom gateway.platforms.shared_ingress import is_wildcard_host@@@ -42,6 -42,6 +45,8 @@@ async def start_tcp_site(runner: web.Barejects an exact duplicate even with SO_REUSEADDR, and a foreign wildcard listener answers theprobe), so one retry with reuse_address=True is safe. A wildcard host keeps the strict path: aforeign listener on a non-loopback interface could not be probed, so it must keep winning."""++ from aiohttp import web++exclusive = sys.platform == "darwin"site = web.TCPSite(runner, host, port, reuse_address=False if exclusive else None)try:diff --cc hermes_cli/profiles.pyindex f1f2203d3ba,806aa7f52d1..d2cc0855f6c--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -990,7 -944,76 +990,76 @@@ def list_profiles(*, lazy_skill_count:return profiles- def profiles_to_serve(multiplex: bool) -> List[Tuple[str, Path]]:+ #: One signature/result per home: the webhook and+ #: api-server callers run :func:`profiles_to_serve` per inbound request, so the reader+ #: must not re-parse a profile's config.yaml every time.+ _STANDALONE_MEMO: Dict[str, Tuple[Optional[tuple], Optional[bool]]] = {}+ _STANDALONE_WARNED = False++ _STANDALONE_DEFAULT_WARNING = (+ "gateway.standalone is ignored on the default profile: it is the host gateway")+++ def profile_is_standalone(home: Path) -> bool:+ """Does ``home``'s own config.yaml opt this profile out of the host multiplexer+ (``gateway.standalone: true``)? Memoised by file signature. The DEFAULT profile is+ never standalone — it IS the host — and warns once per process if the key is set there."""+ global _STANDALONE_WARNED- from yaml import YAMLError++ from hermes_yaml import YAMLError+ from utils import file_signature++ home = Path(home)+ cfg_path = home / "config.yaml"+ key = str(home)+ try:+ signature = file_signature(cfg_path.stat())+ except FileNotFoundError:+ signature = None+ except OSError as exc:+ signature = ("stat-error", exc.errno)+ if _STANDALONE_MEMO.get(key) != (signature, False):+ logger.warning("Cannot read gateway.standalone from %s (%s); treating as not standalone",+ cfg_path, type(exc).__name__)+ _STANDALONE_MEMO[key] = (signature, False)+ return False+ cached = _STANDALONE_MEMO.get(key)+ if cached is not None and cached[0] == signature and cached[1] is not None:+ return cached[1]+ value = None+ if signature is not None:+ from hermes_cli.config import read_user_config_raw+ try:+ cfg = read_user_config_raw(cfg_path) or {}+ except (YAMLError, OSError, UnicodeError) as exc:+ if cached is None or cached[0] != signature:+ logger.warning("Cannot read gateway.standalone from %s (%s); treating as not standalone",+ cfg_path, type(exc).__name__)+ # Access can recover without changing the signature. None retains the+ # warning receipt without caching a transient failure as config.+ _STANDALONE_MEMO[key] = (signature, False if isinstance(exc, YAMLError) else None)+ return False+ if isinstance(cfg.get("gateway"), dict):+ value = cfg["gateway"].get("standalone")+ result = _standalone_truthy(value)+ if home == _get_default_hermes_home():+ if result and not _STANDALONE_WARNED:+ logger.warning(_STANDALONE_DEFAULT_WARNING)+ _STANDALONE_WARNED = True+ result = False+ _STANDALONE_MEMO[key] = (signature, result)+ return result+++ def _standalone_truthy(value: object) -> bool:+ """``gateway.standalone`` truthiness via the shared bool parser; only the+ ``gateway:`` section's ``standalone`` key is read (no top-level alias)."""+ from gateway.config import _bool_token+ if isinstance(value, str):+ return _bool_token(value) is True+ return bool(value)+++ def profiles_to_serve(multiplex: bool, *, include_standalone: bool = False) -> List[Tuple[str, Path]]:"""``(profile_name, hermes_home)`` pairs a gateway should serve — the single chokepointfor "which profiles does the inbound gateway handle".diff --cc tests/gateway/test_host_attach_standalone.pyindex 00000000000,3bc21631824..24f35c5244dmode 000000,100644..100644--- a/tests/gateway/test_host_attach_standalone.py+++ b/tests/gateway/test_host_attach_standalone.py@@@ -1,0 -1,141 +1,141 @@@+ """A configured standalone profile may coexist, but never double-bind a served profile."""++ import os+ from pathlib import Path+ from types import SimpleNamespace++ import pytest++ from gateway import host_attach, host_rendezvous as hr+++ def test_boot_notice_only_labels_configured_standalone_profiles(standalone_home, monkeypatch, caplog):+ from gateway.run import _log_standalone_profiles_at_boot+ from hermes_cli import profiles++ root, solo = standalone_home+ member = root / "profiles" / "member"+ member.mkdir()+ (member / "config.yaml").write_text("{}\n")+ monkeypatch.setattr(profiles, "profiles_to_serve", lambda *a, **kw: [("solo", solo), ("member", member)])+ runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=True), served_profile_names=lambda: ["default"])+ with caplog.at_level("INFO"):+ _log_standalone_profiles_at_boot(runner)+ messages = [r.getMessage() for r in caplog.records if "not served by this gateway" in r.getMessage()]+ assert len(messages) == 1 and "'solo'" in messages[0]++ def broken_roster(*a, **kw):+ raise OSError("unreadable roster")++ monkeypatch.setattr(profiles, "profiles_to_serve", broken_roster)+ _log_standalone_profiles_at_boot(runner)+ assert any(r.levelname == "WARNING" and "boot notice failed" in r.message for r in caplog.records)+++ @pytest.fixture+ def standalone_home(tmp_path, monkeypatch):+ root = tmp_path / "hermes"+ home = root / "profiles" / "solo"+ home.mkdir(parents=True)+ (home / "config.yaml").write_text("gateway:\n standalone: true\n")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ from hermes_cli import profiles+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: root)+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: root / "profiles")+ return root, home+++ @pytest.mark.parametrize("served,known", [(False, True), (True, True), (False, False)])+ def test_standalone_attach_requires_known_unserved_profile(standalone_home, monkeypatch, served, known):+ root, home = standalone_home+ owner = host_attach.HostGateway(os.getpid() + 1, root,+ ("default", "solo") if served else ("default",),+ served_known=known)+ monkeypatch.setattr(host_attach, "host_gateway", lambda **kw: owner)+ requests = []+ monkeypatch.setattr(host_attach, "request_serve_profile", lambda *a, **kw: requests.append(a))+ decision = host_attach.decide(home)+ if known and not served:+ assert decision.outcome == host_attach.START+ else:+ assert decision.outcome == host_attach.REFUSE+ assert decision.transient+ if served:+ assert "rescan-profiles" in decision.message+ assert "30s" in decision.message+ assert requests == [], "an opted-out profile must never ask the host to serve it"++[email protected]_only[email protected]("linux")+ @pytest.mark.parametrize("served,known", [(False, True), (True, True), (False, False)])+ def test_standalone_lock_loser_requires_known_unserved_profile(+ standalone_home, monkeypatch, capsys, served, known,+ ):+ import fcntl+ from gateway import run++ root, home = standalone_home+ owner = host_attach.HostGateway(os.getpid() + 1, root,+ ("default", "solo") if served else ("default",),+ served_known=known)+ monkeypatch.setattr(host_attach, "host_gateway", lambda **kw: owner)+ monkeypatch.setattr(run, "get_hermes_home", lambda: home)+ monkeypatch.setattr(host_attach, "request_serve_profile", lambda *a, **kw: None)+ hr.ensure_host_state_dir()+ with open(hr.lock_path(hr.ROLE_GATEWAY), "a+") as handle:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ if known and not served:+ run._claim_host_gateway_role()+ else:+ with pytest.raises(SystemExit) as exc:+ run._claim_host_gateway_role()+ assert exc.value.code == 75+ if served:+ assert "rescan-profiles" in capsys.readouterr().out++[email protected]_only[email protected]("linux")+ @pytest.mark.parametrize("host_name", ["default", "member"])+ def test_standalone_owner_cannot_hide_a_live_multiplexer(standalone_home, monkeypatch, host_name):+ """A starts first, host starts beside A, then B opts out before the host rescans."""+ import fcntl+ from gateway import run, status++ root, home = standalone_home+ first = root / "profiles" / "first"+ first.mkdir()+ (first / "config.yaml").write_text("gateway:\n standalone: true\n")+ host_home = root if host_name == "default" else root / "profiles" / host_name+ host_home.mkdir(exist_ok=True)+ (host_home / "config.yaml").write_text("{}\n")+ owner = host_attach.HostGateway(os.getpid() + 1, first, ("first",), standalone=True)+ host_pid = os.getpid() + 2+ monkeypatch.setattr(host_attach, "host_gateway", lambda **kw: owner)+ monkeypatch.setattr(status, "live_gateway_pid_for_home",+ lambda h: host_pid if Path(h) == host_home else None)+ identity = {"pid": host_pid, "hermes_home": str(host_home), "profile": host_name,+ "multiplex": True, "served_profiles": ["default", "solo", host_name]}+ monkeypatch.setattr(host_attach, "_identify", lambda h: identity if h == host_home else None)+ monkeypatch.setattr(run, "get_hermes_home", lambda: home)+ hr.ensure_host_state_dir()+ with open(hr.lock_path(hr.ROLE_GATEWAY), "a+") as handle:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ for answer in (identity, None, {**identity, "pid": host_pid + 1}):+ monkeypatch.setattr(host_attach, "_identify", lambda h: answer)+ decision = host_attach.decide(home)+ assert decision.outcome == host_attach.REFUSE+ assert decision.transient+ with pytest.raises(SystemExit) as exc:+ run._claim_host_gateway_role()+ assert exc.value.code == 75+ run._claim_host_gateway_role(force=True)+ # The original lock owner may exit without stopping the multiplexer.+ with monkeypatch.context() as m:+ m.setattr(host_attach, "host_gateway", lambda **kw: None)+ assert host_attach.decide(home).outcome == host_attach.REFUSE+ # Once the live host confirms removal, both entry points permit coexistence.+ identity["served_profiles"] = [host_name]+ monkeypatch.setattr(host_attach, "_identify", lambda h: identity)+ assert host_attach.decide(home).outcome == host_attach.START+ run._claim_host_gateway_role()