Skip to content

The agent that grows with you

fix(gateway): pin the payload launcher row and read its profile past -P

unsupportedpastelsb8e986cb2ba6
diff --git a/gateway/status.py b/gateway/status.py
index c0376d5ec0c..a489555698f 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -673,9 +673,9 @@ def _profile_name_for_home(profile_home: Path) -> Optional[str]:
def profile_flag_value(command: str) -> Optional[str]:
- """The ``-p``/``--profile`` argument of a command line, or None. Token equality is the only safe
- profile match: a substring test lets ``-p ops`` claim (and ``gateway stop`` SIGTERM) ``-p ops-2``."""
- tokens = command.split()
+ """Lowercased ``-p``/``--profile`` argument of a case-preserved command line (a bootstrap's interpreter
+ ``-P`` is no ``-p``, #127865), or None. Token equality: ``-p ops`` must not claim ``-p ops-2``."""
+ tokens = [t.lower() for t in inline_bootstrap_argv(command.split()) or command.split()]
for i, tok in enumerate(tokens):
if tok.startswith("--profile="):
return tok.partition("=")[2]
@@ -720,7 +720,7 @@ def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:
profile_name = _profile_name_for_home(profile_home)
home_lc = str(profile_home).lower().replace("\\", "/").rstrip("/")
if profile_name is not None and profile_name != "default":
- if profile_flag_value(command_lc) == profile_name.lower():
+ if profile_flag_value(command) == profile_name.lower():
return True
return command_line_names_hermes_home(command_lc, home_lc)
# Default profile: accept unless argv names ANOTHER profile (any spelling the CLI pre-parser
@@ -729,7 +729,7 @@ def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:
# arrives via the env). ``--profile default`` names this profile: a hand-written launchd plist
# mirrors the named-profile service shape, and rejecting it reported a live default gateway
# as stopped (#100817).
- if profile_flag_value(command_lc) not in (None, "default"):
+ if profile_flag_value(command) not in (None, "default"):
return False
return not hermes_home_assignments(command_lc) or command_line_names_hermes_home(command_lc, home_lc)
diff --git a/gateway/status_inline_source.py b/gateway/status_inline_source.py
index 64671584529..8adb59b0f13 100644
--- a/gateway/status_inline_source.py
+++ b/gateway/status_inline_source.py
@@ -89,11 +89,13 @@ _BOOTSTRAPS = (
("exec", re.compile(r"import sys, runpy; sys\.path\.insert\(.*?;\s*exec\((?P<target>.+)\)", re.DOTALL)),
# hermes_cli._launchers._launcher_script (the published POSIX shell / Windows .cmd launcher)
("entry", re.compile(r"import os, re, sys\s.*\bfrom\s+(?P<target>[\w.]+)\s+import\s+(?P<func>\w+)\b.*\bsys\.exit\(\s*(?P=func)\(\)\s*\)", re.DOTALL)),
- # scripts/build/launchers.py::posix_launcher (the bundled/Docker payload's bin/hermes)
- ("entry", re.compile(
- r"import os, site, sys;.*\bsite\.addsitedir\(os\.environ\[['\"]HERMES_SITE['\"]\]\);"
- r"\s*from\s+(?P<target>[\w.]+)\s+import\s+(?P<func>\w+)\s*;\s*sys\.exit\(\s*(?P=func)\(\)\s*\)",
- re.DOTALL)),
+ # scripts/build/launchers.py::posix_launcher (the bundled/Docker payload's bin/hermes). Spelled out
+ # statement by statement: a ``.*`` would span a carrier's source plus the launcher argv it carries.
+ # Only the ``hermes`` entry: the same shape importing any other module is someone else's program.
+ ("module", re.compile(
+ rf"import os, site, sys;\s*sys\.argv\[0\]\s*=\s*{_Q}[\w.-]+{_Q};\s*"
+ rf"site\.addsitedir\(os\.environ\[{_Q}HERMES_SITE{_Q}\]\);"
+ r"\s*from\s+(?P<target>hermes_cli\.main)\s+import\s+main\s*;\s*sys\.exit\(\s*main\(\)\s*\)")),
# hermes_cli._launchers._write_cmd_launcher: the launcher script, base64-encoded
("base64", re.compile(rf"import base64; exec\(base64\.b64decode\({_Q}(?P<target>[A-Za-z0-9+/=]+){_Q}\)\)")),
)
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 7b9caf44aae..5a952c3d291 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -600,7 +600,7 @@ def _scan_gateway_pids(
command_lc = command.lower().replace("\\", "/")
if current_profile_name:
# Token equality, not substring: `-p ops` must not claim (or SIGTERM) an `-p ops-2` gateway.
- if profile_flag_value(command_lc) == current_profile_name_lc:
+ if profile_flag_value(command) == current_profile_name_lc:
return True
return command_line_names_hermes_home(command_lc, current_home_lc)
@@ -608,7 +608,7 @@ def _scan_gateway_pids(
# accepts (``--profile=ops`` slipped past a substring test, so a default-profile fallback stop
# could SIGTERM the named gateway) or a HERMES_HOME= naming another home. An explicit
# ``--profile default`` names this home (#100817).
- if profile_flag_value(command_lc) not in (None, "default"):
+ if profile_flag_value(command) not in (None, "default"):
return False
if hermes_home_assignments(command_lc):
return command_line_names_hermes_home(command_lc, current_home_lc)
diff --git a/tests/gateway/test_gateway_inline_bootstrap_identity.py b/tests/gateway/test_gateway_inline_bootstrap_identity.py
index 6ffc0a7bd70..8347c23f7be 100644
--- a/tests/gateway/test_gateway_inline_bootstrap_identity.py
+++ b/tests/gateway/test_gateway_inline_bootstrap_identity.py
@@ -2,7 +2,8 @@
The store launcher (``_launchers.runtime_command``, also the Windows updater's relaunch), the
published launcher script (POSIX shell launcher and the Windows ``.cmd`` base64 wrapper) and the
-``venv_sync`` re-entry all run ``python -I -c <source> …`` with the entry point IN that process.
+``venv_sync`` re-entry and the bundled/Docker payload's ``bin/hermes`` (``scripts/build/launchers``,
+#127865) all run ``python -c <source> …`` with the entry point IN that process.
The #107002 guard that keeps an inline program's trailing argv as data made all of them invisible.
The readers hand the matchers different strings: ``/proc``, psutil and ``ps`` space-join argv (the
source splits across tokens); Windows CIM reports the CreateProcess line (``list2cmdline``).
@@ -11,12 +12,16 @@ source splits across tokens); Windows CIM reports the CreateProcess line (``list
from __future__ import annotations
import base64
+import json
+import shlex
import subprocess
from pathlib import Path
import pytest
-from gateway.status import looks_like_gateway_command_line
+from gateway import status
+from gateway.status import looks_like_gateway_command_line, looks_like_gateway_runtime_command_line
+from gateway.status_inline_source import inline_bootstrap_argv
from hermes_cli import _launchers, venv_sync
from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
@@ -26,6 +31,17 @@ _SCRIPT = _launchers._launcher_script("hermes", ROOT, None)
_JOINS = {"space-joined": " ".join, "windows": subprocess.list2cmdline}
+def _payload_launcher(argv: list[str]) -> list[str]:
+ """The payload ``bin/hermes`` exec line, rendered by the real payload builder."""
+ from scripts.build.launchers import posix_launcher
+
+ script = posix_launcher("hermes", "hermes_cli.main:main", python="tools/python/bin/python3",
+ repo="hermes-agent", site="venv/lib/python3.14/site-packages", target="linux-x64")
+ exec_line = next(line for line in script.splitlines() if line.startswith("exec "))
+ _, _python, *launch, _args = shlex.split(exec_line)
+ return [PY, *launch, *argv]
+
+
def _forms(argv: list[str]) -> dict[str, list[str]]:
forms = {
"store-launcher": _launchers.runtime_command(ROOT, argv, python=Path(PY)),
@@ -34,6 +50,7 @@ def _forms(argv: list[str]) -> dict[str, list[str]]:
"venv-reentry": venv_sync.relaunch_command(
Path(PY), ROOT, [str(ROOT / "hermes_cli" / "main.py"), *argv], ["/old/python", "-m", "hermes_cli.main", *argv],
"hermes_cli.main"),
+ "payload-launcher": _payload_launcher(argv),
}
# A launch through a published launcher that synced dependencies first re-enters it via exec().
for name in ("launcher-script", "cmd-launcher"):
@@ -68,3 +85,87 @@ def test_bundled_posix_launcher_bootstrap_is_a_gateway() -> None:
)
command_line = " ".join([PY, "-P", "-c", source, "gateway", "run", "--replace"])
assert looks_like_gateway_command_line(command_line)
+
+
+
+_GATEWAY = (["gateway", "run"], ["gateway", "run", "--replace"], ["--profile", "work", "gateway", "run"],
+ ["-p", "work", "gateway", "run"], ["gateway", "run", "-p", "work"])
+_NOT_GATEWAY = (["gateway", "status"], ["gateway", "stop"], ["status"], ["chat"])
+
+
[email protected]("join", _JOINS)
[email protected]("argv", [*_GATEWAY, ["gateway", "restart"], *_NOT_GATEWAY], ids=" ".join)
+def test_payload_launcher_reads_as_the_hermes_command_it_runs(argv: list[str], join: str) -> None:
+ command_line = _JOINS[join](_payload_launcher(argv))
+ # ``gateway restart`` hosts the runtime in-process without a service manager, but is no ``run``.
+ assert looks_like_gateway_command_line(command_line) is (argv in _GATEWAY)
+ assert looks_like_gateway_runtime_command_line(command_line) is (argv in (*_GATEWAY, ["gateway", "restart"]))
+
+
[email protected]("split", [list, lambda argv: " ".join(argv).split(" ")], ids=["argv", "space-split"])
+def test_payload_launcher_maps_to_the_module_spelling(split) -> None:
+ tokens = split(_payload_launcher(["gateway", "run", "--replace"]))
+ assert inline_bootstrap_argv(tokens) == [PY, "-m", "hermes_cli.main", "gateway", "run", "--replace"]
+
+
[email protected]("join", _JOINS)
[email protected]("module", ["not_hermes_cli.main", "foreign.hermes_cli.main", "hermes_cli.main_x"])
+def test_payload_launcher_shape_with_another_entry_module_is_not_hermes(module: str, join: str) -> None:
+ launch = _payload_launcher(["gateway", "run"])
+ launch[launch.index("-c") + 1] = launch[launch.index("-c") + 1].replace(
+ "from hermes_cli.main import", f"from {module} import")
+ command_line = _JOINS[join](launch)
+ assert inline_bootstrap_argv(launch) is None
+ assert not looks_like_gateway_command_line(command_line)
+ assert _hermes_holder_subcommand(command_line) is None
+
+
[email protected]("join", _JOINS)
[email protected]("carrier", [
+ "import os, sys, time\npid = int(sys.argv[1]); cmd = sys.argv[2:]\n", # the restart watcher (#107002)
+ "import os, site, sys; cmd = sys.argv[2:]", # opens like the payload bootstrap, runs no entry point
+], ids=["restart-watcher", "payload-lookalike"])
+def test_a_program_carrying_the_payload_launcher_is_not_a_gateway(carrier: str, join: str) -> None:
+ carried = [PY, "-c", carrier, "1234", *_payload_launcher(["gateway", "run"])]
+ command_line = _JOINS[join](carried)
+ assert inline_bootstrap_argv(carried) is None
+ assert not looks_like_gateway_command_line(command_line)
+ assert _hermes_holder_subcommand(command_line) is None
+
+
[email protected]("argv,expected", [
+ ([], None), (["gateway", "run"], None), (["-p", "work", "gateway", "run"], "work"),
+ (["gateway", "run", "--profile=Work"], "work"),
+])
+def test_payload_launcher_profile_is_read_from_the_hermes_argv(argv: list[str], expected: str | None) -> None:
+ # ``/proc`` space-joins argv; the interpreter's ``-P`` before ``-c`` is no ``-p`` (#127865).
+ assert status.profile_flag_value(" ".join(_payload_launcher(argv))) == expected
+
+
[email protected]("argv,profile,found", [
+ (["gateway", "run"], None, True),
+ (["-p", "work", "gateway", "run"], "work", True),
+ (["-p", "work", "gateway", "run"], None, False), # another profile's gateway is not the default's
+ (["chat"], None, False),
+], ids=["default", "named", "other-profile", "chat"])
+def test_live_payload_launched_gateway_is_found_for_its_home(argv, profile, found, tmp_path, monkeypatch) -> None:
+ """The dashboard / ``gateway stop`` / ``restart`` lookup: the live ``/proc`` cmdline of a gateway
+ started through the payload ``bin/hermes`` proves its home's runtime record (#127865)."""
+ import hermes_constants
+
+ root = tmp_path / ".hermes"
+ home = root / "profiles" / profile if profile else root
+ home.mkdir(parents=True)
+ monkeypatch.setattr(hermes_constants.Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None, raising=False)
+ record = {
+ "pid": 4242, "kind": "hermes-gateway", "gateway_state": "running", "start_time": 1000,
+ "argv": ["/opt/hermes/hermes-agent/hermes_cli/main.py", *argv], "hermes_home": str(home),
+ }
+ (home / "gateway_state.json").write_text(json.dumps(record), encoding="utf-8")
+ monkeypatch.setattr(status, "_pid_exists", lambda pid: pid == 4242)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 1000)
+ monkeypatch.setattr(status, "_read_process_cmdline", lambda pid: " ".join(_payload_launcher(argv)))
+
+ assert status.live_gateway_pid_for_home(home) == (4242 if found else None)