The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: ensure a gateway without installing or replacing services
Teknium6f2910803516
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.pyindex 24383e42fef..e14047a547b 100644--- a/hermes_cli/gateway_runtime.py+++ b/hermes_cli/gateway_runtime.py@@ -94,6 +94,69 @@ def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0)return GatewayDiscovery("inaccessible", reason_code="control_timeout")except DiscoveryError as exc:return GatewayDiscovery("inaccessible", reason_code=exc.reason)+ except PermissionError:+ return GatewayDiscovery("inaccessible", reason_code="authorization")except (OSError, ValueError, TypeError):# Raw peer data, paths and URLs may contain secrets; report bounded codes.return GatewayDiscovery("inaccessible", reason_code="invalid_control_peer")+++def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = 30.0) -> GatewayDiscovery:+ """Ensure once, never install/replace; pending remains pending at deadline.++ A successful service command or Popen is not session readiness. After an+ owner/start request is observed this invocation never launches another.+ """+ import time+ from hermes_cli.gateway_runtime_service import (+ RuntimeStartError, discover_existing_gateway_service, remaining,+ start_existing_gateway_service,+ )+ from hermes_cli.update_lock import MARKER_NAME+ from hermes_constants import get_default_hermes_root, get_process_hermes_home++ if not math.isfinite(timeout) or timeout <= 0:+ raise ValueError("timeout must be finite and positive")+ deadline = time.monotonic() + timeout+ home = Path(_canonical_home(profile_home))+ requested = False+ delay = 0.025+ try:+ while True:+ # Never clear the updater's fence, even if malformed. Repair is not+ # a client operation. The install-root marker also covers profiles.+ for fence_home in {home, get_process_hermes_home(), get_default_hermes_root()}:+ try:+ (fence_home / MARKER_NAME).lstat()+ except FileNotFoundError:+ continue+ return GatewayDiscovery("draining", reason_code="update_paused")+ observed = discover_gateway_endpoint(home, timeout=remaining(deadline))+ if observed.reason_code == "control_timeout":+ return GatewayDiscovery("starting", reason_code="deadline")+ if observed.state not in {"absent", "starting"}:+ return observed+ if observed.state == "starting":+ requested = True+ if observed.state == "absent" and not requested:+ service = discover_existing_gateway_service(home, deadline=deadline)+ # Runtime locks settle races remaining after this second probe.+ observed = discover_gateway_endpoint(home, timeout=remaining(deadline))+ if observed.state != "absent":+ continue+ if service is not None:+ start_existing_gateway_service(service, deadline=deadline)+ else:+ from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway+ spawn_unmanaged_gateway(home, deadline=deadline)+ requested = True+ time.sleep(min(delay, remaining(deadline)))+ delay = min(delay * 1.5, 0.25)+ except TimeoutError:+ return GatewayDiscovery("starting", reason_code="deadline")+ except RuntimeStartError as exc:+ return GatewayDiscovery(exc.state, reason_code=exc.reason)+ except PermissionError:+ return GatewayDiscovery("inaccessible", reason_code="authorization")+ except OSError:+ return GatewayDiscovery("inaccessible", reason_code="runtime_start_failed")diff --git a/hermes_cli/gateway_runtime_cli.py b/hermes_cli/gateway_runtime_cli.pynew file mode 100644index 00000000000..23f1dc9d0a9--- /dev/null+++ b/hermes_cli/gateway_runtime_cli.py@@ -0,0 +1,32 @@+"""Machine-readable ensure boundary. No bootstrap credentials leave this command."""+from dataclasses import asdict+import json+import sys+from contextlib import redirect_stdout+++def ensure_exit_code(result) -> int:+ if result.reason_code == "deadline":+ return 5+ if result.reason_code in {"authorization", "profile_mismatch"}:+ return 4+ return {"ready": 0, "incompatible": 3, "draining": 6,+ "inaccessible": 7, "conflict": 7, "starting": 5, "absent": 5}[result.state]+++def cmd_gateway_ensure(args) -> None:+ from hermes_constants import get_hermes_home+ from hermes_cli.gateway_runtime import ensure_gateway_runtime++ try:+ # Legacy imported utilities can print; protocol stdout belongs only to us.+ with redirect_stdout(sys.stderr):+ result = ensure_gateway_runtime(get_hermes_home(), timeout=float(args.timeout))+ payload = asdict(result)+ if result.endpoint:+ payload["endpoint"]["capabilities"] = sorted(result.endpoint.capabilities)+ code = ensure_exit_code(result)+ except (ValueError, TypeError):+ payload, code = {"state": "inaccessible", "reason_code": "invalid_invocation", "endpoint": None}, 2+ print(json.dumps(payload, separators=(",", ":"), sort_keys=True))+ raise SystemExit(code)diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.pyindex 2092bfbc99d..0a77fc08a86 100644--- a/hermes_cli/gateway_runtime_discovery.py+++ b/hermes_cli/gateway_runtime_discovery.py@@ -59,7 +59,9 @@ def _socket_path(home: Path) -> Path:def query_identify(home: Path, *, timeout: float) -> dict:"""Unlike diagnostic queries, retain timeout/access/protocol failures."""if os.name == "nt":- raise DiscoveryError("native_bootstrap_required")+ from gateway.runtime_bootstrap_windows import query_runtime_control+ return _identify_response(query_runtime_control(+ home, b'{"protocol":1,"verb":"identify","id":1}\n', timeout))deadline = time.monotonic() + timeoutpath = _socket_path(home)request = b'{"protocol":1,"verb":"identify","id":1}\n'@@ -79,7 +81,11 @@ def query_identify(home: Path, *, timeout: float) -> dict:data.extend(chunk)if len(data) > 524288:raise DiscoveryError("oversized_control_response")- response = json.loads(bytes(data).split(b"\n", 1)[0])+ return _identify_response(bytes(data))+++def _identify_response(data: bytes) -> dict:+ response = json.loads(data.split(b"\n", 1)[0])if (not isinstance(response, dict) or response.get("ok") is not Trueor response.get("protocol") != 1 or response.get("id") != 1or not isinstance(response.get("result"), dict)):@@ -87,7 +93,15 @@ def query_identify(home: Path, *, timeout: float) -> dict:return response["result"]-def missing_owner_state(home: Path) -> Literal["starting", "absent"]:- """A live old owner without an API is not permission to start another."""- from gateway.status import get_running_pid- return "starting" if get_running_pid(home / "gateway.pid", cleanup_stale=False) else "absent"+def missing_owner_state(home: Path) -> Literal["starting", "absent", "inaccessible"]:+ """A reservation before PID/control publication already excludes a new owner."""+ from gateway.status import _is_gateway_runtime_lock_active_strict+ lock = home / "gateway.lock"+ try:+ if os.name != "nt":+ _private_node(lock, kind="file")+ return "starting" if _is_gateway_runtime_lock_active_strict(lock) else "absent"+ except FileNotFoundError:+ return "absent"+ except (OSError, RuntimeError, DiscoveryError):+ return "inaccessible"diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.pynew file mode 100644index 00000000000..20d60c210db--- /dev/null+++ b/hermes_cli/gateway_runtime_service.py@@ -0,0 +1,179 @@+"""Non-installing service-manager operations for an explicit canonical profile.++The legacy start helpers refresh units, regenerate plists, or fall back to+unmanaged processes. Client startup must not call those helpers.+"""+from __future__ import annotations++import csv+from dataclasses import dataclass+import hashlib+import io+import os+from pathlib import Path+import plistlib+import subprocess+import sys+import time++from gateway.runtime_contract import RuntimeState+from hermes_cli._subprocess_compat import windows_hide_flags+++class RuntimeStartError(RuntimeError):+ def __init__(self, reason: str, state: RuntimeState = "inaccessible"):+ super().__init__(reason)+ self.reason, self.state = reason, state+++def remaining(deadline: float) -> float:+ budget = deadline - time.monotonic()+ if budget <= 0:+ raise TimeoutError+ return budget+++def service_suffix(home: Path) -> str:+ from hermes_constants import get_default_hermes_root+ from hermes_cli.gateway import _profile_name_from_home+ default = get_default_hermes_root().resolve()+ home = home.resolve()+ if home == default:+ return ""+ return _profile_name_from_home(home, default) or hashlib.sha256(str(home).encode()).hexdigest()[:8]+++@dataclass(frozen=True)+class ExistingService:+ backend: str+ start_argv: tuple[str, ...]+ running: bool = False+++def _run(argv: list[str] | tuple[str, ...], deadline: float):+ return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ creationflags=windows_hide_flags(), timeout=remaining(deadline))+++def _exists(path: Path) -> bool:+ try:+ path.lstat()+ return True+ except FileNotFoundError:+ return False+++def _systemd(home: Path, deadline: float) -> ExistingService | None:+ from hermes_cli import gateway as gw+ from hermes_cli.service_manager import _s6_running+ if _s6_running():+ raise RuntimeStartError("external_supervisor")+ suffix = service_suffix(home)+ unit = f"hermes-gateway{'-' + suffix if suffix else ''}.service"+ paths = (Path.home() / ".config/systemd/user" / unit, Path("/etc/systemd/system") / unit)+ # On non-systemd hosts there is no manager to own transient units. Installed+ # definitions still count: a broken manager is not permission to bypass one.+ manager_paths = (Path("/run/systemd/system"),+ Path(f"/run/user/{os.getuid()}/systemd/private")) # windows-footgun: ok — native systemd only+ if not any(_exists(p) for p in (*paths, *manager_paths)):+ return None+ found = []+ for system in (False, True):+ command = gw._systemctl_cmd(system)+ result = _run([*command, "show", unit, "--no-pager",+ "--property=LoadState,ActiveState,SubState,UnitFileState"], deadline)+ props = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)+ if props.get("LoadState") == "not-found" and not _exists(paths[int(system)]):+ continue+ if result.returncode or props.get("LoadState") != "loaded":+ raise RuntimeStartError("service_manager_unavailable")+ if props.get("UnitFileState") in {"masked", "masked-runtime"}:+ raise RuntimeStartError("service_masked")+ state = props.get("ActiveState")+ if state == "deactivating":+ raise RuntimeStartError("service_draining", "draining")+ if state not in {"inactive", "active", "activating", "reloading", "failed"}:+ raise RuntimeStartError("service_state_unknown")+ if state == "failed":+ raise RuntimeStartError("service_failed")+ found.append(ExistingService("systemd", tuple([*command, "--no-ask-password", "start", unit]),+ state != "inactive"))+ if len(found) > 1:+ raise RuntimeStartError("service_scope_conflict", "conflict")+ return found[0] if found else None+++def _launchd(home: Path, deadline: float) -> ExistingService | None:+ import pwd+ suffix = service_suffix(home)+ label = f"ai.hermes.gateway{'-' + suffix if suffix else ''}"+ account_home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — native launchd only+ plist = account_home / "Library/LaunchAgents" / f"{label}.plist"+ installed = _exists(plist)+ if installed:+ with plist.open("rb") as stream:+ definition = plistlib.load(stream)+ configured = definition.get("EnvironmentVariables", {}).get("HERMES_HOME")+ if not configured or Path(configured).resolve() != home or definition.get("Label") != label:+ raise RuntimeStartError("profile_mismatch")+ if definition.get("Disabled"):+ raise RuntimeStartError("service_disabled")+ domains = [f"gui/{os.getuid()}", f"user/{os.getuid()}"] # windows-footgun: ok — native launchd only+ for domain in domains:+ result = _run(["launchctl", "print", f"{domain}/{label}"], deadline)+ if result.returncode == 0:+ return ExistingService("launchd", ("launchctl", "kickstart", f"{domain}/{label}"),+ "state = running" in result.stdout)+ # launchctl's native absent-service code; other errors retain uncertainty.+ if result.returncode != 113:+ raise RuntimeStartError("service_manager_unavailable")+ if installed:+ # Load ONLY the existing file, never bootout/rewrite or kickstart -k.+ return ExistingService("launchd", ("launchctl", "bootstrap", domains[0], str(plist)))+ return None+++def _windows(home: Path, deadline: float) -> ExistingService | None:+ from hermes_cli.gateway_windows import _startup_dir+ suffix = service_suffix(home)+ name = f"Hermes_Gateway{'_' + suffix if suffix else ''}"+ result = _run(["schtasks.exe", "/Query", "/FO", "CSV", "/NH"], deadline)+ if result.returncode:+ raise RuntimeStartError("service_manager_unavailable")+ rows = list(csv.reader(io.StringIO(result.stdout)))+ if any(len(row) != 3 for row in rows if row):+ raise RuntimeStartError("service_state_unknown")+ if any(row and row[0].lstrip("\\") == name for row in rows):+ return ExistingService("windows", ("schtasks.exe", "/Run", "/TN", name))+ # Startup-folder entries are installed persistence too, but have no independent+ # start supervisor. Do not bypass them with a job-bound unmanaged child.+ if any(_exists(_startup_dir() / f"{name}.{ext}") for ext in ("cmd", "vbs")):+ raise RuntimeStartError("startup_service_requires_login")+ return None+++def discover_existing_gateway_service(home: Path, *, deadline: float) -> ExistingService | None:+ backend = {"linux": _systemd, "darwin": _launchd, "win32": _windows}.get(sys.platform)+ if backend is None:+ raise RuntimeStartError("unsupported_supervisor_platform")+ try:+ return backend(home, deadline)+ except subprocess.TimeoutExpired:+ raise TimeoutError from None+ except (OSError, ValueError) as exc:+ raise RuntimeStartError("service_manager_unavailable") from exc+++def start_existing_gateway_service(service: ExistingService, *, deadline: float) -> None:+ """Request start once; only live control readiness can establish success."""+ if service.running:+ return+ try:+ result = _run(service.start_argv, deadline)+ except subprocess.TimeoutExpired:+ raise TimeoutError from None+ except OSError as exc:+ raise RuntimeStartError("service_start_failed") from exc+ if result.returncode:+ raise RuntimeStartError("service_start_failed")diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.pynew file mode 100644index 00000000000..5d3fb31685b--- /dev/null+++ b/hermes_cli/gateway_runtime_start.py@@ -0,0 +1,45 @@+"""One detached-process primitive; callers must first prove owner/service absence."""+from __future__ import annotations++import os+from pathlib import Path+import subprocess+import sys++from hermes_cli._subprocess_compat import windows_detach_popen_kwargs, _WINDOWS_GATEWAY_BREAKAWAY_ENV+from hermes_cli.gateway_runtime_service import RuntimeStartError, remaining+++def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float) -> subprocess.Popen:+ """Request a daemon, not readiness. Refuse Windows no-breakaway fallback.++ No --replace, persistence, login changes, elevation, shell, or inherited stdio.+ The gateway runtime's own exclusive ownership fence arbitrates racing starts.+ """+ home = profile_home.resolve()+ root = Path(__file__).resolve().parent.parent+ command = [sys.executable, "-m", "hermes_cli.main", "gateway", "run", "--quiet"]+ env = dict(os.environ)+ if sys.platform == "win32":+ from hermes_cli.gateway_windows import windowless_gateway_restart_spec+ command, _, overlay = windowless_gateway_restart_spec(command)+ if not overlay:+ raise RuntimeStartError("windows_interpreter_unavailable")+ env.update(overlay)+ env[_WINDOWS_GATEWAY_BREAKAWAY_ENV] = "1"+ env.update(HERMES_HOME=str(home), HERMES_GATEWAY_DETACHED="1", PYTHONIOENCODING="utf-8")+ # Profile selection is the explicit home, not the invoking client's display+ # name. Runtime policy comes from that profile, never a launcher's --yolo.+ env.pop("HERMES_PROFILE", None)+ remaining(deadline)+ logs = home / "logs"+ logs.mkdir(parents=True, exist_ok=True)+ try:+ with (logs / "gateway-stdio.log").open("ab", buffering=0) as output:+ remaining(deadline)+ return subprocess.Popen(command, cwd=root, env=env, close_fds=True,+ stdin=subprocess.DEVNULL, stdout=output, stderr=output,+ **windows_detach_popen_kwargs())+ except OSError as exc:+ reason = "windows_breakaway_unavailable" if sys.platform == "win32" else "spawn_failed"+ raise RuntimeStartError(reason) from excdiff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.pyindex 0eeb8dd0ccd..a7fa976d083 100644--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@ -61,6 +61,17 @@ def build_gateway_parser(add_accept_hooks_flag(gateway_run)add_accept_hooks_flag(gateway_parser)+ from hermes_cli.gateway_runtime_cli import cmd_gateway_ensure+ gateway_ensure = gateway_subparsers.add_parser(+ "ensure", help="Ensure a local runtime without installing or replacing a service",+ epilog="Exit codes: 0 ready; 2 invalid invocation; 3 incompatible; "+ "4 authorization/profile mismatch; 5 deadline; 6 draining/update-paused; "+ "7 inaccessible/conflicting supervisor. Pending startup is not readiness.")+ _flag(gateway_ensure, "--json", help="Emit one credential-free JSON result (default)")+ gateway_ensure.add_argument("--timeout", default="30",+ help="Total startup deadline in seconds (default: 30)")+ gateway_ensure.set_defaults(func=cmd_gateway_ensure)+gateway_start = gateway_subparsers.add_parser("start", help="Start the installed systemd/launchd background service")_add_system_flag(gateway_start)diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.pynew file mode 100644index 00000000000..d0c056da3ad--- /dev/null+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py@@ -0,0 +1,202 @@+"""Real local-control and subprocess boundaries, never real service mutations."""+import asyncio+import json+import os+from pathlib import Path+import subprocess+import sys+import time++import pytest++[email protected]_only+def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(tmp_path):+ from gateway.control_socket import GatewayControlServer+ from hermes_cli import gateway_runtime as runtime++ assert callable(getattr(runtime, "ensure_gateway_runtime", None))++ async def probe():+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ payload = {"runtime_protocol": 1, "state": "starting", "instance_id": "peer",+ "served_profiles": [{"profile_id": str(home), "home": str(home)}]}+ server = GatewayControlServer(home, verb_handlers={"identify": lambda: payload})+ assert await server.start()+ try:+ before = time.monotonic()+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=0.3)+ assert result.state == "starting" and result.reason_code == "deadline"+ assert time.monotonic() - before < 2+ payload["state"] = "draining"+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=0.3)+ assert result.state == "draining"+ payload["served_profiles"] = []+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=0.3)+ assert result.state == "inaccessible" and result.reason_code == "profile_mismatch"+ assert not (home / "logs").exists()+ finally:+ await server.stop()+ asyncio.run(probe())++[email protected]_only+def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(tmp_path, monkeypatch):+ from hermes_cli import gateway as gw, gateway_runtime as runtime++ assert callable(getattr(runtime, "ensure_gateway_runtime", None))+ from hermes_cli.gateway_runtime_service import service_suffix+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ monkeypatch.setenv("HERMES_HOME", str(home))+ unit = tmp_path / ".config/systemd/user" / f"hermes-gateway-{service_suffix(home)}.service"+ unit.parent.mkdir(parents=True)+ unit.write_text("[Service]\nExecStart=/owned/inert/gateway\n", encoding="utf-8")+ original = unit.read_bytes()+ calls = tmp_path / "calls.jsonl"+ helper = tmp_path / "inert-supervisor"+ helper.write_text('#!' + sys.executable + '\nimport json,sys\nfrom pathlib import Path\n'+ + f'p=Path({str(calls)!r})\n'+ + 'with p.open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'+ + 'if (p.parent/"fail").exists(): print("private-supervisor-token"); sys.exit(3)\n'+ + 'if "show" in sys.argv and "system" in sys.argv and (p.parent/"single").exists():\n print("LoadState=not-found")\n'+ + 'elif "show" in sys.argv:\n print("LoadState=loaded\\nActiveState=inactive\\nSubState=dead\\nUnitFileState=enabled")\n'+ + 'elif "start" in sys.argv: sys.exit(0)\n'+ + 'else: sys.exit(91)\n', encoding="utf-8")+ helper.chmod(0o700)+ monkeypatch.setattr(gw, "_systemctl_cmd", lambda system=False: [str(helper), "system" if system else "user"])+ result = runtime.ensure_gateway_runtime(home, timeout=0.4)+ # Both scopes claiming this name is a conflict, never permission to choose one.+ assert result.state == "conflict"+ assert unit.read_bytes() == original+ assert not (home / "logs").exists()+ assert all("show" in json.loads(line) for line in calls.read_text().splitlines())+ (tmp_path / "single").touch()+ result = runtime.ensure_gateway_runtime(home, timeout=0.5)+ assert result.state == "starting" and result.reason_code == "deadline"+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1+ assert unit.read_bytes() == original+ assert not (home / "logs").exists()+ (tmp_path / "fail").touch()+ result = runtime.ensure_gateway_runtime(home, timeout=0.5)+ assert result.state == "inaccessible" and result.reason_code == "service_manager_unavailable"+ assert "private-supervisor-token" not in repr(result)+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1+ assert not (home / "logs").exists()++[email protected]_only+def test_public_ensure_json_deadline_and_invalid_invocation(tmp_path):+ from hermes_cli import gateway_runtime as runtime+ assert callable(getattr(runtime, "ensure_gateway_runtime", None))+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ (home / ".hermes-update-in-progress").write_text("private-token-not-for-stdout", encoding="utf-8")+ env = {**os.environ, "HERMES_HOME": str(home)}+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json"],+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 6, result.stderr+ value = json.loads(result.stdout)+ assert value["state"] == "draining" and value["reason_code"] == "update_paused"+ assert "private-token" not in result.stdout+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json", "--timeout", "nan"],+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 2+ assert json.loads(result.stdout)["reason_code"] == "invalid_invocation"++[email protected]_only+def test_unmanaged_child_uses_explicit_home_and_survives_launcher_exit(tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_start as start+ assert callable(getattr(start, "spawn_unmanaged_gateway", None))+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ witness = home / "child.json"+ gate = home / "exit"+ launcher = tmp_path / "launcher.py"+ launcher.write_text(+ "import json,os,sys,time\nfrom pathlib import Path\n"+ "from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway\n"+ "import hermes_cli.gateway_runtime_start as start\n"+ f"home=Path({str(home)!r})\n"+ "real=start.subprocess.Popen\n"+ "def boundary(argv, **kw):\n"+ " assert argv[-3:] == ['gateway','run','--quiet']\n"+ " assert '--replace' not in argv and '--force' not in argv\n"+ " assert kw['env']['HERMES_HOME'] == str(home)\n"+ " code=\"import os,json,time; from pathlib import Path; h=Path(os.environ['HERMES_HOME']); (h/'child.json').write_text(json.dumps({'pid':os.getpid(),'sid':os.getsid(0),'home':str(h)}));\\nwhile not (h/'exit').exists(): time.sleep(.02)\"\n"+ " return real([sys.executable,'-c',code], **kw)\n"+ "start.subprocess.Popen=boundary\n"+ "child=spawn_unmanaged_gateway(home, deadline=time.monotonic()+5)\n"+ "print(child.pid, flush=True)\n", encoding="utf-8")+ env = {**os.environ, "PYTHONPATH": str(Path.cwd()), "HERMES_HOME": str(tmp_path / "wrong")}+ result = subprocess.run([sys.executable, str(launcher)], env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=10)+ try:+ assert result.returncode == 0, result.stderr+ deadline = time.monotonic() + 5+ while not witness.exists() and time.monotonic() < deadline:+ time.sleep(.02)+ value = json.loads(witness.read_text())+ assert value["pid"] == int(result.stdout) == value["sid"]+ assert value["home"] == str(home)+ finally:+ gate.touch()++[email protected]_only+def test_reserved_profile_without_pid_or_control_is_never_absent(tmp_path):+ from gateway.runtime_ownership import ProfileOwnership+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ home = tmp_path / "reserved"+ home.mkdir(mode=0o700)+ owner = ProfileOwnership()+ owner.reserve([home])+ try:+ assert not (home / "gateway.pid").exists()+ assert discover_gateway_endpoint(home).state == "starting"+ (home / "gateway.lock").chmod(0)+ assert discover_gateway_endpoint(home).state == "inaccessible"+ finally:+ (home / "gateway.lock").chmod(0o600)+ owner.close()+ assert discover_gateway_endpoint(home).state == "absent"++[email protected]_only+def test_native_windows_discovery_uses_same_user_pipe(tmp_path):+ from gateway.runtime_bootstrap_windows import NativeControlServer+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ home = tmp_path.resolve()+ def handle(raw, subject):+ assert subject.startswith("sid:")+ request = json.loads(raw)+ assert request["verb"] == "identify"+ return json.dumps({"protocol": 1, "id": 1, "ok": True, "result": {+ "runtime_protocol": 1, "state": "starting", "instance_id": "native-peer",+ "served_profiles": [{"home": str(home), "profile_id": str(home)}]+ }}).encode() + b"\n"+ server = NativeControlServer(home, handle)+ server.start()+ try:+ assert discover_gateway_endpoint(home, timeout=2).state == "starting"+ finally:+ server.close()++[email protected]_only+def test_native_windows_spawn_never_retries_without_breakaway(tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_start as start+ from hermes_cli.gateway_runtime_service import RuntimeStartError+ from hermes_cli._subprocess_compat import windows_detach_flags+ calls = []+ def denied(argv, **kwargs):+ calls.append(kwargs)+ raise PermissionError("job forbids breakaway")+ monkeypatch.setattr(start.subprocess, "Popen", denied)+ with pytest.raises(RuntimeStartError, match="windows_breakaway_unavailable"):+ start.spawn_unmanaged_gateway(tmp_path, deadline=time.monotonic()+5)+ assert len(calls) == 1+ assert calls[0]["creationflags"] == windows_detach_flags()