The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): every launchd-identity reader accepts the wrapper-forwarded label
teknium167f385f2d80f
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 0230e6f9b33..28d982214eb 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -87,8 +87,8 @@ def _detect_supervisor() -> str:env = os.environif env.get("INVOCATION_ID"):return "systemd"- if sys.platform == "darwin" and (env.get("XPC_SERVICE_NAME", "").startswith("ai.hermes")- or env.get("LAUNCHD_SOCKET")):+ from gateway.restart import launchd_job_label+ if sys.platform == "darwin" and (launchd_job_label(env) or env.get("LAUNCHD_SOCKET")):return "launchd"if env.get("HERMES_DESKTOP_MANAGED"):return "desktop"diff --git a/gateway/restart.py b/gateway/restart.pyindex 160dae4ba22..57732284c3d 100644--- a/gateway/restart.py+++ b/gateway/restart.py@@ -36,9 +36,8 @@ def map_fatal_config_exit_for_launchd(returncode: int) -> int:# environment (e.g. ``sudo env -i``).EXTERNAL_GATEWAY_SUPERVISOR_ENV = "HERMES_GATEWAY_EXTERNAL_SUPERVISOR"-# Re-exported by the stderr-timestamp launchd wrapper (hermes_cli/stderr_timestamp.py).-# launchd stamps ``XPC_SERVICE_NAME`` only on the wrapper itself; the gateway grandchild-# sees ``XPC_SERVICE_NAME=0`` and would otherwise be invisible to the drain cap.+# Forwarded by the stderr-timestamp launchd wrapper (hermes_cli/stderr_timestamp.py) to the gateway+# grandchild, which sees ``XPC_SERVICE_NAME=0``. Read only via :func:`launchd_job_label`.LAUNCHD_LABEL_ENV = "HERMES_LAUNCHD_LABEL"DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["restart_drain_timeout"])@@ -89,32 +88,35 @@ def parse_launchd_exit_timeout(print_output: object) -> float | None:return float(match.group(1))-def launchd_service_label(environ: Mapping[str, str] | None = None) -> str | None:- """Return this process's ``ai.hermes.*`` launchd job label, or ``None``.+def launchd_job_label(environ: Mapping[str, str] | None = None) -> str | None:+ """The ``ai.hermes.*`` launchd job label in *environ*, or ``None`` (no darwin gate).++ launchd stamps ``XPC_SERVICE_NAME`` only on the job process it spawns. The generated plist+ runs the stderr-timestamp wrapper there, so the gateway grandchild reads ``XPC_SERVICE_NAME=0``+ and finds its label only in the wrapper's re-export, ``HERMES_LAUNCHD_LABEL``. Both go through+ the same ``ai.hermes`` predicate: app-coalition labels (``application.<bundle>…``, exported+ into IDE integrated terminals) are not our job. ONE seam for every reader of launchd identity+ (drain cap, restart route, control-socket supervisor declaration).+ """+ env = os.environ if environ is None else environ+ for var in ("XPC_SERVICE_NAME", LAUNCHD_LABEL_ENV):+ label = str(env.get(var, "") or "").strip()+ if label.startswith("ai.hermes"):+ return label+ return None- Only labels of the gateway's own jobs count (same predicate as- :mod:`gateway.control_socket`). App-coalition labels- (``application.<bundle>…``, exported into IDE integrated terminals) also- populate ``XPC_SERVICE_NAME``, and ``launchctl print`` reports- ``exit timeout = 1`` for them — treating those as a budget would cap the- drain to 0 for a gateway Ctrl+C'd in such a terminal.- When this process is a launchd grandchild (the generated plist runs the- stderr-timestamp wrapper as the job process), ``XPC_SERVICE_NAME`` reads- ``"0"`` and the wrapper's re-exported ``HERMES_LAUNCHD_LABEL`` is used.+def launchd_service_label(environ: Mapping[str, str] | None = None, *, platform: str = sys.platform) -> str | None:+ """Return this process's ``ai.hermes.*`` launchd job label, or ``None`` off darwin.++ ``launchctl print`` reports ``exit timeout = 1`` for app-coalition labels — treating those as+ a budget would cap the drain to 0 for a gateway Ctrl+C'd in an IDE terminal, hence the+ predicate in :func:`launchd_job_label`. ``platform`` is data so the mapping logic is testable+ on any host."""- if sys.platform != "darwin":+ if platform != "darwin":return None- env = os.environ if environ is None else environ- label = str(env.get("XPC_SERVICE_NAME", "") or "").strip()- if not label.startswith("ai.hermes"):- # Under the generated launchd plist the gateway is a grandchild (the stderr-timestamp- # wrapper is the job process), so XPC_SERVICE_NAME reads "0" here; the wrapper- # re-exports the real job label for exactly this fallback.- label = str(env.get(LAUNCHD_LABEL_ENV, "") or "").strip()- if not label.startswith("ai.hermes"):- return None- return label+ return launchd_job_label(environ)def read_launchd_exit_timeout_s(@@ -123,15 +125,16 @@ def read_launchd_exit_timeout_s(environ: Mapping[str, str] | None = None,uid: int | None = None,run: Callable[..., "subprocess.CompletedProcess[str]"] = subprocess.run,+ platform: str = sys.platform,) -> float | None:"""Live ``ExitTimeOut`` (seconds) launchd enforces for this gateway's job.Returns ``None`` — meaning "no launchd budget applies" — when the process- is not launchd-owned (non-darwin, or no ``ai.hermes`` ``XPC_SERVICE_NAME``), ``launchctl`` is missing+ is not launchd-owned (non-darwin, or no ``ai.hermes`` job label — see :func:`launchd_job_label`), ``launchctl`` is missingor fails, or the print output carries no ``exit timeout`` line. Callersmust treat ``None`` as fail-open: the configured drain stands unchanged."""- label = label or launchd_service_label(environ)+ label = label or launchd_service_label(environ, platform=platform)if not label:return Noneif uid is None:@@ -239,7 +242,8 @@ def is_gateway_supervisor_process(environ: Mapping[str, str] | None = None) -> b"""Return whether this gateway process is owned by a supervisor that RESTARTS it.Selects the exit-75 restart route, so only markers of a manager with a restart policy count:- systemd ``INVOCATION_ID``, launchd ``XPC_SERVICE_NAME``, the s6 sentinel, or the explicit+ systemd ``INVOCATION_ID``, launchd ``XPC_SERVICE_NAME`` (or the wrapper-forwarded+ ``HERMES_LAUNCHD_LABEL`` the grandchild sees), the s6 sentinel, or the explicit``--external-supervisor`` opt-in. The generalized ``HERMES_SUPERVISED_CHILD`` launcher marker isdeliberately NOT read here: the Windows Scheduled-Task launcher sets it without a restart policy(#113670), and routing its ``/restart`` through exit 75 would leave the gateway dead.@@ -247,6 +251,7 @@ def is_gateway_supervisor_process(environ: Mapping[str, str] | None = None) -> benv = os.environ if environ is None else environxpc_service = env.get("XPC_SERVICE_NAME", "")return bool(env.get("INVOCATION_ID") or env.get("HERMES_S6_SUPERVISED_CHILD") or (xpc_service and xpc_service != "0")+ or launchd_job_label(env)or str(env.get(EXTERNAL_GATEWAY_SUPERVISOR_ENV, "")).strip().lower() in _TRUTHY)diff --git a/hermes_cli/stderr_timestamp.py b/hermes_cli/stderr_timestamp.pyindex 04bcd72f4eb..5343b8c3bc9 100644--- a/hermes_cli/stderr_timestamp.py+++ b/hermes_cli/stderr_timestamp.py@@ -15,8 +15,6 @@ from typing import BinaryIO, Sequence, TextIOEXTERNAL_SUPERVISOR_FLAG = "--external-supervisor"-# gateway/restart.py reads this to size the stop drain to the job's live ExitTimeOut.-LAUNCHD_LABEL_ENV = "HERMES_LAUNCHD_LABEL"_TIMESTAMP_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}(?:\s|$)")@@ -93,15 +91,15 @@ def _child_launchd_label_env(environ: Mapping[str, str] | None = None) -> dict[slaunchd stamps ``XPC_SERVICE_NAME=<job label>`` only on this wrapper (its direct child; aninteractive shell has none, the grandchild sees ``XPC_SERVICE_NAME=0``). Re-exporting the- label lets the gateway resolve its job without it (e.g. the stop-drain cap reading the- live ``ExitTimeOut`` in gateway/restart.py). Only ``ai.hermes.*`` labels are exported;+ label lets the gateway resolve its job without it (the stop-drain cap reading the live+ ``ExitTimeOut``, the exit-75 restart route, the control-socket supervisor declaration — all+ via ``gateway.restart.launchd_job_label``). Only ``ai.hermes.*`` labels are exported;app-coalition labels are meaningless as a job identity."""- env = os.environ if environ is None else environ- label = str(env.get("XPC_SERVICE_NAME", "") or "").strip()- if not label.startswith("ai.hermes"):- return {}- return {LAUNCHD_LABEL_ENV: label}+ from gateway.restart import LAUNCHD_LABEL_ENV, launchd_job_label++ label = launchd_job_label(os.environ if environ is None else environ)+ return {LAUNCHD_LABEL_ENV: label} if label else {}def _prepare_child_command(command: Sequence[str], environ: Mapping[str, str] | None = None) -> list[str]:diff --git a/tests/gateway/test_launchd_exit_timeout_drain_cap.py b/tests/gateway/test_launchd_exit_timeout_drain_cap.pyindex 6e56f33e2c9..1df5fc08502 100644--- a/tests/gateway/test_launchd_exit_timeout_drain_cap.py+++ b/tests/gateway/test_launchd_exit_timeout_drain_cap.py@@ -22,6 +22,7 @@ from gateway.restart import (LAUNCHD_STOP_CLEANUP_RESERVE_S,effective_stop_drain_timeout,effective_stop_watchdog_delay,+ is_gateway_supervisor_process,launchd_service_label,read_launchd_exit_timeout_s,resolve_launchd_capped_drain,@@ -29,7 +30,17 @@ from gateway.restart import (from gateway.shutdown_watchdog import resolve_shutdown_watchdog_delay-def test_capped_drain_fits_inside_launchd_budget_minus_reserve():+ "platform, label, expected",+ [+ ("darwin", "ai.hermes.gateway", 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S),+ # App-coalition label (IDE integrated terminal) is not our job: no budget, drain unchanged.+ ("darwin", "application.com.example.ide.123", 180.0),+ # launchd is darwin-only (same predicate as control_socket): a leaked label elsewhere is ignored.+ ("linux", "ai.hermes.gateway", 180.0),+ ],+)+def test_capped_drain_fits_inside_launchd_budget_minus_reserve(platform, label, expected):# The incident shape: configured 180s, launchd clamps to 60s.assert resolve_launchd_capped_drain(180.0, 60.0) == 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S# Never extends a short drain; no launchd budget leaves the configured drain alone.@@ -39,48 +50,39 @@ def test_capped_drain_fits_inside_launchd_budget_minus_reserve():def _read_budget(label):fake_run = lambda *a, **k: SimpleNamespace(returncode=0, stdout="exit timeout = 60\n") # noqa: E731- return read_launchd_exit_timeout_s(environ={"XPC_SERVICE_NAME": label}, uid=501, run=fake_run)+ budget = read_launchd_exit_timeout_s(environ={"XPC_SERVICE_NAME": label}, uid=501, run=fake_run, platform=platform)+ assert resolve_launchd_capped_drain(180.0, budget) == expected[email protected]_only- "label, expected",- [- ("ai.hermes.gateway", 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S),- # App-coalition label (IDE integrated terminal) is not our job: no budget, drain unchanged.- ("application.com.example.ide.123", 180.0),- ],-)-def test_launchd_reader_yields_a_budget_only_for_hermes_jobs(label, expected):- assert resolve_launchd_capped_drain(180.0, _read_budget(label)) == expected--[email protected]_only-def test_launchd_label_leaked_onto_linux_is_ignored():- assert _read_budget("ai.hermes.gateway") is None---def test_grandchild_resolves_label_from_wrapper_reexport(monkeypatch):- """Under the generated plist the gateway is a grandchild: launchd stamps XPC_SERVICE_NAME- only on the stderr-timestamp wrapper, the grandchild reads "0", and the wrapper re-exports- the job label as HERMES_LAUNCHD_LABEL so the drain cap still resolves its budget."""- monkeypatch.setattr(restart_mod.sys, "platform", "darwin")+def test_grandchild_resolves_label_from_wrapper_reexport():+ """Under the generated plist the gateway is a grandchild: launchd stamps XPC_SERVICE_NAME only on+ the stderr-timestamp wrapper, the grandchild reads "0", and the wrapper forwards the job label as+ HERMES_LAUNCHD_LABEL so the drain cap still resolves its budget. Platform is data, not the host."""grandchild_env = {"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "ai.hermes.gateway"}- assert launchd_service_label(grandchild_env) == "ai.hermes.gateway"- # The re-export keeps the ai.hermes predicate: an app-coalition label is still not our job.- assert launchd_service_label({"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "application.com.example.ide.123"}) is None- # No fallback at all (foreground start, or a wrapper older than the re-export) stays None.- assert launchd_service_label({"XPC_SERVICE_NAME": "0"}) is None- # A direct launchd child (no wrapper) keeps the XPC path.- assert launchd_service_label({"XPC_SERVICE_NAME": "ai.hermes.gateway"}) == "ai.hermes.gateway"+ assert launchd_service_label(grandchild_env, platform="darwin") == "ai.hermes.gateway"+ # The forwarded label keeps the ai.hermes predicate: an app-coalition label is still not our job.+ assert launchd_service_label({"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "application.com.example.ide.123"},+ platform="darwin") is None+ # No label at all (foreground start, or a wrapper older than the forward) stays None; so does linux.+ assert launchd_service_label({"XPC_SERVICE_NAME": "0"}, platform="darwin") is None+ assert launchd_service_label(grandchild_env, platform="linux") is None# End to end: the grandchild sizes its stop drain to the live ExitTimeOut.fake_run = lambda *a, **k: SimpleNamespace(returncode=0, stdout="exit timeout = 60\n") # noqa: E731- budget = read_launchd_exit_timeout_s(environ=grandchild_env, uid=501, run=fake_run)+ budget = read_launchd_exit_timeout_s(environ=grandchild_env, uid=501, run=fake_run, platform="darwin")assert resolve_launchd_capped_drain(180.0, budget) == 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S+def test_forwarded_label_marks_grandchild_supervised_for_every_reader():+ """One seam: the restart route and the control-socket declaration see the same launchd identity+ the drain cap does, so a grandchild is not 'manual' to one reader and 'launchd' to another."""+ grandchild_env = {"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "ai.hermes.gateway"}+ assert is_gateway_supervisor_process(grandchild_env) is True+ assert is_gateway_supervisor_process({"XPC_SERVICE_NAME": "0"}) is False+ assert is_gateway_supervisor_process({"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "application.com.x.1"}) is False++def _runner(*, drain: float, launchd: float | None, by_signal: bool):return SimpleNamespace(_restart_drain_timeout=drain, _launchd_exit_timeout_s=launchd, _stop_requested_by_signal=by_signal,diff --git a/tests/hermes_cli/test_stderr_timestamp.py b/tests/hermes_cli/test_stderr_timestamp.pyindex 9fb4f4e3af5..0e1e8b3ca55 100644--- a/tests/hermes_cli/test_stderr_timestamp.py+++ b/tests/hermes_cli/test_stderr_timestamp.py@@ -13,6 +13,7 @@ from gateway.restart import (EXTERNAL_GATEWAY_SUPERVISOR_ENV,GATEWAY_FATAL_CONFIG_EXIT_CODE,GATEWAY_SERVICE_RESTART_EXIT_CODE,+ LAUNCHD_LABEL_ENV,)from hermes_cli import stderr_timestamp@@ -91,61 +92,31 @@ def test_prepare_skips_interactive_xpc_zero_even_for_gateway_argv():def test_child_launchd_label_env_exports_only_hermes_job_labels():- assert stderr_timestamp._child_launchd_label_env(_LAUNCHD_ENV) == {- stderr_timestamp.LAUNCHD_LABEL_ENV: "ai.hermes.gateway-butler"- }- # Interactive shells and the grandchild itself read "0": nothing to export.- assert stderr_timestamp._child_launchd_label_env({"PATH": "/usr/bin", "XPC_SERVICE_NAME": "0"}) == {}- assert stderr_timestamp._child_launchd_label_env({"PATH": "/usr/bin"}) == {}- # App-coalition labels (IDE integrated terminals) are not a Hermes job identity.- assert (- stderr_timestamp._child_launchd_label_env(- {"PATH": "/usr/bin", "XPC_SERVICE_NAME": "application.com.example.ide.123"}- )- == {}- )---def test_main_exports_launchd_label_to_child(tmp_path, monkeypatch):- """The gateway grandchild must resolve its job (drain cap) from HERMES_LAUNCHD_LABEL."""- monkeypatch.setenv("XPC_SERVICE_NAME", "ai.hermes.gateway-butler")- monkeypatch.delenv(stderr_timestamp.LAUNCHD_LABEL_ENV, raising=False)- log_path = tmp_path / "gateway.error.log"- marker_path = tmp_path / "label.txt"- code = (- "import os\n"- f"from pathlib import Path\n"- f"Path({str(marker_path)!r}).write_text("- f"os.environ.get({stderr_timestamp.LAUNCHD_LABEL_ENV!r}, 'unset'), encoding='utf-8')\n"- )-- rc = stderr_timestamp.main(- ["--error-log", str(log_path), "--", sys.executable, "-c", code]- )-- assert rc == 0- assert marker_path.read_text(encoding="utf-8") == "ai.hermes.gateway-butler"---def test_main_does_not_fabricate_label_for_xpc_zero(tmp_path, monkeypatch):- """Foreground/unsupervised starts must not inherit a fabricated job label."""- monkeypatch.setenv("XPC_SERVICE_NAME", "0")- monkeypatch.delenv(stderr_timestamp.LAUNCHD_LABEL_ENV, raising=False)- log_path = tmp_path / "gateway.error.log"+ assert stderr_timestamp._child_launchd_label_env(_LAUNCHD_ENV) == {LAUNCHD_LABEL_ENV: "ai.hermes.gateway-butler"}+ # Interactive shells and the grandchild itself read "0": nothing to export. App-coalition labels+ # (IDE integrated terminals) are not a Hermes job identity either.+ for env in ({"PATH": "/usr/bin", "XPC_SERVICE_NAME": "0"}, {"PATH": "/usr/bin"},+ {"PATH": "/usr/bin", "XPC_SERVICE_NAME": "application.com.example.ide.123"}):+ assert stderr_timestamp._child_launchd_label_env(env) == {}++[email protected]("xpc, expected", [("ai.hermes.gateway-butler", "ai.hermes.gateway-butler"), ("0", "unset")],+ ids=["launchd-job", "foreground-xpc-zero"])+def test_main_forwards_launchd_label_to_child_only_under_launchd(tmp_path, monkeypatch, xpc, expected):+ """The gateway grandchild must resolve its job (drain cap, restart route) from HERMES_LAUNCHD_LABEL;+ a foreground/unsupervised start must not inherit a fabricated one."""+ monkeypatch.setenv("XPC_SERVICE_NAME", xpc)+ monkeypatch.delenv(LAUNCHD_LABEL_ENV, raising=False)marker_path = tmp_path / "label.txt"code = (- "import os\n"- f"from pathlib import Path\n"- f"Path({str(marker_path)!r}).write_text("- f"os.environ.get({stderr_timestamp.LAUNCHD_LABEL_ENV!r}, 'unset'), encoding='utf-8')\n"+ "import os\nfrom pathlib import Path\n"+ f"Path({str(marker_path)!r}).write_text(os.environ.get({LAUNCHD_LABEL_ENV!r}, 'unset'), encoding='utf-8')\n")- rc = stderr_timestamp.main(- ["--error-log", str(log_path), "--", sys.executable, "-c", code]- )+ rc = stderr_timestamp.main(["--error-log", str(tmp_path / "gateway.error.log"), "--", sys.executable, "-c", code])assert rc == 0- assert marker_path.read_text(encoding="utf-8") == "unset"+ assert marker_path.read_text(encoding="utf-8") == expected# The child is ``python -c <record argv>`` carrying a "gateway run" tail as inert data, which is