Skip to content

The agent that grows with you

merge origin/main (15 commits) into ethie/pm-clean

ethernet9d036f8ac90c
diff --cc gateway/host_rendezvous.py
index 10213ffc392,64d9bca9890..fbe9c616214
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@@ -239,9 -289,12 +289,12 @@@ def probe_owner(record: HostRecord, *,
def read_record(role: str, *, include_stale: bool = False) -> Optional[HostRecord]:
- """Published record for ``role``; ``None`` when absent, corrupt or (by default) stale."""
+ """Published record for ``role``; ``None`` when absent, foreign, corrupt or (by default) stale."""
+ path = record_path(role)
+ if not _record_is_own(path):
+ return None
try:
- raw = record_path(role).read_text(encoding="utf-8-sig")
- raw = path.read_text(encoding="utf-8")
++ raw = path.read_text(encoding="utf-8-sig")
except (OSError, UnicodeDecodeError):
return None
try:
diff --cc hermes_cli/gateway_launchd.py
index 7ca4f1fef08,cd60588545d..20094606c4b
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@@ -207,11 -208,33 +208,34 @@@ def _launchd_unsupported_marker_exists(
def _gateway_run_command() -> list[str]:
- """Build ``python -m hermes_cli.main [--profile X] gateway run --replace``, honoring the active profile."""
- return [_gw().get_python_path(), "-m", "hermes_cli.main", *_gw()._profile_arg().split(), "gateway", "run", "--replace"]
+ from hermes_cli._launchers import runtime_command
+ return runtime_command(_gw().PROJECT_ROOT, [*shlex.split(_gw()._profile_arg()), "gateway", "run", "--replace"],
+ python=_gw().get_python_path())
+ def launchd_program_arguments(command: list[str], stdout_log: Path, stderr_log: Path) -> list[str]:
+ """launchd ``ProgramArguments`` that run ``command`` with a Local Network identity macOS accepts (#71206).
+
+ macOS Local Network Privacy attributes a socket to the process launchd spawned for the job. A bare
+ venv Python has no application ID and is not platform-entitled, so every LAN connect from the
+ launchd gateway dies with ``EHOSTUNREACH`` while the same code works from Terminal (whose grant it
+ inherits). An ad-hoc-signed helper .app does not help: nehelper never prompts for it and denies
+ (#57812 dead-end table, re-verified live on macOS 26.3). ``/usr/bin/osascript``'s ``do shell script``
+ spawns its child as osascript-responsible — an Apple platform binary — so the child is exempt;
+ ``/bin/sh -c exec …`` and ``/usr/bin/time`` wrappers are NOT (the launchd job identity is the
+ non-entitled first executable). ``do shell script`` buffers the child's stdout/stderr until it exits,
+ so the command appends both to the same files the plist's ``StandardOutPath``/``StandardErrorPath``
+ name (those keys stay: they are where osascript's own output lands — an empty result line per exit
+ and an un-timestamped ``execution error`` line on non-zero exit); ``exec`` keeps the
+ gateway a direct child in the job's process group, so ``launchctl bootout`` / ``kickstart -k`` still
+ deliver SIGTERM to it and KeepAlive's ``SuccessfulExit`` semantics are preserved (osascript exits 0
+ exactly when the shell did).
+ """
+ shell = f"exec {shlex.join(command)} >> {shlex.quote(str(stdout_log))} 2>> {shlex.quote(str(stderr_log))}"
+ applescript = shell.replace("\\", "\\\\").replace('"', '\\"')
+ return ["/usr/bin/osascript", "-e", f'do shell script "{applescript}"']
+
+
def _timestamped_stderr_gateway_command(error_log: Path, *, external_supervisor: bool = False) -> list[str]:
"""Wrap gateway run so raw stderr lines are timestamped before file write. ``external_supervisor``
(launchd ProgramArguments only) adds ``--external-supervisor`` so ``hermes update`` hands back to
diff --cc scripts/run_tests.sh
index 1f67ba4afab,bc0b4e6b98f..fe01385ef1e
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@@ -168,7 -144,7 +168,7 @@@ _pf86="$(env | sed -n 's/^ProgramFiles(
TEST_ENV=()
for _test_var in HERMES_TEST_IMAGE HERMES_TEST_WORKERS HERMES_TEST_PATHS \
HERMES_TEST_FILE_TIMEOUT HERMES_TEST_FILE_RETRIES HERMES_TEST_SLICE \
- SSL_CERT_FILE SSL_CERT_DIR; do
- HERMES_GATEWAY_LOCK_DIR; do
++ SSL_CERT_FILE SSL_CERT_DIR HERMES_GATEWAY_LOCK_DIR; do
if [ -n "${!_test_var:-}" ]; then
TEST_ENV+=("$_test_var=${!_test_var}")
fi
diff --cc tests/conftest.py
index 7a8edd1a6e1,ae7af042a82..ba916fa5cc4
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -141,17 -120,53 +141,49 @@@ os.environ["HERMES_TEST_ISOLATION"] = o
#: even with this block removed.
HERMES_HOME_AT_CONFTEST_IMPORT = os.environ.get("HERMES_HOME", "")
+ # ── Host-rendezvous isolation ───────────────────────────────────────────────
+ # ``gateway/host_rendezvous.py`` publishes ONE record per role per OS USER, in
+ # ``$HERMES_GATEWAY_LOCK_DIR`` else ``$XDG_STATE_HOME/hermes/gateway-locks`` —
+ # deliberately outside HERMES_HOME, because the host singleton spans profiles.
+ # Under the per-file parallel runner that directory is shared by ~40 pytest
+ # subprocesses: one test that boots a real gateway publishes a record, and every
+ # other file's lifecycle code then correctly attaches to a gateway that has
+ # nothing to do with it. Give each pytest PROCESS its own rendezvous dir.
+ #
+ # A caller-supplied value always wins (both here and in the per-test fixture
+ # below) — otherwise the documented override is a silent no-op.
+ HOST_LOCK_DIR_AT_CONFTEST_IMPORT = os.environ.get("HERMES_GATEWAY_LOCK_DIR", "")
+ if not HOST_LOCK_DIR_AT_CONFTEST_IMPORT:
+ # Deterministic per-PID name, not mkdtemp: the parallel runner SIGKILLs a worker on timeout,
+ # which never runs atexit, so a random dir per run leaked one directory per killed worker.
+ # A fixed name is reused by the next process with that PID, and dead siblings are swept here.
+ _LOCK_DIR_PREFIX = "hermes-test-gateway-locks-"
+ _LOCK_DIR_ROOT = Path(tempfile.gettempdir())
+ for _stale in _LOCK_DIR_ROOT.glob(f"{_LOCK_DIR_PREFIX}*"):
+ try:
+ _stale_pid = int(_stale.name[len(_LOCK_DIR_PREFIX):])
+ except ValueError:
+ continue
+ try:
+ os.kill(_stale_pid, 0)
+ except OSError:
+ shutil.rmtree(_stale, ignore_errors=True)
+ _SESSION_LOCK_DIR = str(_LOCK_DIR_ROOT / f"{_LOCK_DIR_PREFIX}{os.getpid()}")
+ shutil.rmtree(_SESSION_LOCK_DIR, ignore_errors=True)
+ os.environ["HERMES_GATEWAY_LOCK_DIR"] = _SESSION_LOCK_DIR
+ atexit.register(shutil.rmtree, _SESSION_LOCK_DIR, True)
+
-# ── Per-file process isolation ──────────────────────────────────────────────
-# Tests run via ``scripts/run_tests_parallel.py``, which spawns a fresh
-# ``python -m pytest <file>`` subprocess per test file. Cross-file state
-# leakage (module-level dicts, ContextVars, caches) is impossible: each
-# file gets a clean Python interpreter. Intra-file ordering is the test
-# author's responsibility — if test A in foo.py mutates state that test B
-# in foo.py reads, that's a real bug to fix in the file (it would also
-# bite anyone running ``pytest tests/foo.py`` directly).
+# ── File-level scheduling isolation ──────────────────────────────────────────
+# Tests run via ``scripts/run_tests.sh``, which runs the per-file runner
+# (``scripts/run_tests_parallel.py``) on every host: every file in its own
+# freshly-spawned ``python -m pytest <file>`` subprocess — cross-file state
+# leakage is impossible. Intra-file ordering is the test author's
+# responsibility on every host — if test A in foo.py mutates state that
+# test B in foo.py reads, that's a real bug to fix in the file (it would
+# also bite anyone running ``pytest tests/foo.py`` directly).
#
-# This replaces the historic _reset_module_state autouse fixture (manual
-# state clearing) and the brief experiment with subprocess-per-test
-# isolation (too slow at ~17k tests).
-#
-# See ``scripts/run_tests_parallel.py`` for the runner.
+# See ``scripts/run_tests.sh`` for the runner.
# ── Credential env-var filter ──────────────────────────────────────────────
diff --cc tests/hermes_cli/test_gateway_service.py
index 7932a44fbca,e27048a761a..76fd2d31f5d
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@@ -1,8 -1,9 +1,10 @@@
"""Tests for gateway service management helpers."""
+import json
import os
import plistlib
+ import re
+ import shlex
import subprocess
from pathlib import Path
from types import SimpleNamespace
@@@ -1866,12 -1859,46 +1881,37 @@@ class TestProfileArg
plist = gateway_cli.generate_launchd_plist()
program_args = plistlib.loads(plist.encode("utf-8"))["ProgramArguments"]
+ # The job is launched through osascript so macOS Local Network Privacy attributes the
- # gateway's sockets to a platform binary (#71206); the real command is the exec'd child.
- assert _osascript_exec_argv(program_args) == [
- "/usr/bin/python3",
- "-m",
- "hermes_cli.stderr_timestamp",
- "--error-log",
- str(profile_dir / "logs" / "gateway.error.log"),
- "--",
- "/usr/bin/python3",
- "-m",
- "hermes_cli.main",
- "--profile",
- "mybot",
- "gateway",
- "run",
- "--external-supervisor",
- ">>",
- str(profile_dir / "logs" / "gateway.log"),
- "2>>",
- str(profile_dir / "logs" / "gateway.error.log"),
- ]
++ # gateway's sockets to a platform binary (#71206); the real command is the exec'd child,
++ # whose python runs through the PM installation launcher (-I -c bootstrap ...).
++ exec_argv = _osascript_exec_argv(program_args)
++ assert exec_argv[-4:] == [">>", str(profile_dir / "logs" / "gateway.log"),
++ "2>>", str(profile_dir / "logs" / "gateway.error.log")]
++ program_args = exec_argv[:-4]
+ assert program_args[0] == "/usr/bin/python3"
+ assert program_args[-5:] == ["--profile", "mybot", "gateway", "run", "--external-supervisor"]
+ separator = program_args.index("--")
++
+ assert program_args[separator - 2:separator] == ["--error-log", str(profile_dir / "logs" / "gateway.error.log")]
+ assert "--replace" not in program_args
+ def test_launchd_osascript_wrapper_round_trips_shell_hostile_paths(self, tmp_path, monkeypatch):
+ """A home with spaces, quotes and a backslash survives shlex + AppleScript + plist quoting."""
+ profile_dir = tmp_path / 'my "odd" dir \\ here' / ".hermes"
+ profile_dir.mkdir(parents=True)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(profile_dir))
+ monkeypatch.setattr(gateway_cli, "get_hermes_home", lambda: profile_dir)
+ monkeypatch.setattr(gateway_cli, "get_python_path", lambda: str(profile_dir / "bin dir" / "python"))
+
+ program_args = plistlib.loads(gateway_cli.generate_launchd_plist().encode("utf-8"))["ProgramArguments"]
+ argv = _osascript_exec_argv(program_args)
+
+ assert argv[0] == str(profile_dir / "bin dir" / "python")
+ assert argv[-3:] == [str(profile_dir / "logs" / "gateway.log"), "2>>", str(profile_dir / "logs" / "gateway.error.log")]
+ # The wrapper's own ps line must never be taken for the gateway (stop/status would signal osascript).
+ assert status.looks_like_gateway_command_line(" ".join(program_args)) is False
+
def test_launchd_plist_path_uses_real_user_home_not_profile_home(self, tmp_path, monkeypatch):
profile_dir = tmp_path / ".hermes" / "profiles" / "orcha"
profile_dir.mkdir(parents=True)