Skip to content

The agent that grows with you

fix(update): exempt gateways from separate checkouts

fangliquanflq561658d26d87
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 585d03a3e16..c2fe2f72bed 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -131,10 +131,13 @@ def _receipt_reports_stale_runtime(receipt: dict, expected_sha: str | None = Non
def _sha_mismatch(code_sha) -> bool:
return bool(code_sha) and str(code_sha) != str(expected_sha)
+ from hermes_cli.update_receipt import row_is_external
+
fleet = receipt.get("fleet")
if isinstance(fleet, list) and fleet:
return any(
isinstance(entry, dict)
+ and not row_is_external(entry)
and (entry.get("state") == "stale" or _sha_mismatch(entry.get("code_sha")))
for entry in fleet
)
@@ -205,7 +208,7 @@ def _live_fleet_covers_receipt(expected_sha: str | None, receipt: dict, owed: se
"""Require a successor at the expected SHA for every owed gateway identity."""
if not expected_sha:
return False
- from hermes_cli.update_receipt import collect_fleet_versions
+ from hermes_cli.update_receipt import collect_fleet_versions, row_is_external
try:
if owed is None:
@@ -216,7 +219,7 @@ def _live_fleet_covers_receipt(expected_sha: str | None, receipt: dict, owed: se
# State labels are checkout-relative; completed restarts may accept stale rows at the pulled SHA.
if not fleet or any(
row.get("state") not in accept_states or row.get("code_sha") != expected_sha
- for row in fleet
+ for row in fleet if not row_is_external(row)
):
return False
covered = _fleet_covered_gateways(fleet)
@@ -285,7 +288,7 @@ def _marker_only_restart_obsolete() -> bool:
if not target_sha:
return False
try:
- from hermes_cli.update_receipt import collect_fleet_versions
+ from hermes_cli.update_receipt import collect_fleet_versions, row_is_external
fleet = collect_fleet_versions()
except Exception as exc:
logger.debug("Fleet probe failed; keeping fleet-restart-pending marker: %s", exc)
@@ -296,6 +299,8 @@ def _marker_only_restart_obsolete() -> bool:
if covered is None:
return False # unidentified runtime: the matrix cannot vouch for it
for row in fleet:
+ if row_is_external(row):
+ continue
if row.get("state") != "current" or str(row.get("code_sha")) != target_sha:
return False # stale / down / unknown-identity row still owes the restart
if owed is not None and not owed <= covered:
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 06d7ed86363..0c06c368c2c 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -294,15 +294,83 @@ def _socket_identity(home: Path) -> Optional[tuple[int, dict]]:
return None
+_CODE_ROOT_MAX_DEPTH = 8
+
+
+def _code_root_for_path(raw: Any) -> Optional[Path]:
+ """Return the Hermes checkout containing an absolute process path."""
+ if not isinstance(raw, str) or not raw:
+ return None
+ with suppress(Exception):
+ candidate = Path(raw)
+ if not candidate.is_absolute():
+ return None
+ for parent in [candidate, *candidate.parents][:_CODE_ROOT_MAX_DEPTH]:
+ if (parent / "hermes_cli" / "main.py").is_file():
+ return parent.resolve()
+ return None
+
+
+def _updater_code_root() -> Optional[Path]:
+ return _code_root_for_path(str(Path(__file__).resolve()))
+
+
+def _gateway_code_root(pid: int, home: Path) -> Optional[Path]:
+ """Resolve the checkout served by a verified live gateway when possible."""
+ # Older gateways cannot publish a new identity field, but their pid-guarded
+ # status record already carries sys.argv (whose first item is the resolved
+ # module path for ``python -m`` launches).
+ with suppress(Exception):
+ from gateway.status import read_runtime_status
+
+ record = read_runtime_status(home / "gateway_state.json") or {}
+ if int(record.get("pid")) == pid:
+ for probe in record.get("argv") or []:
+ root = _code_root_for_path(probe)
+ if root:
+ return root
+
+ with suppress(Exception):
+ import psutil # type: ignore
+
+ process = psutil.Process(pid)
+ with suppress(Exception):
+ root = _code_root_for_path((process.environ() or {}).get("VIRTUAL_ENV"))
+ if root:
+ return root
+ probes: list[Any] = []
+ with suppress(Exception):
+ probes.append(process.exe())
+ with suppress(Exception):
+ probes.extend(process.cmdline() or [])
+ for probe in probes:
+ root = _code_root_for_path(probe)
+ if root:
+ return root
+ return None
+
+
+EXTERNAL_STATE = "external"
+
+
+def row_is_external(row: Any) -> bool:
+ """Whether a fleet row serves a checkout this update did not touch."""
+ return isinstance(row, dict) and row.get("state") == EXTERNAL_STATE
+
+
def _fleet_row(
profile: str, pid: int, code_sha: Any, code_version: Any, expected_sha: Any,
- state: str = "unknown", served_profiles: Any = None,
+ state: str = "unknown", code_root: Optional[Path] = None,
+ expected_root: Optional[Path] = None, served_profiles: Any = None,
) -> dict[str, Any]:
+ if state == "unknown" and code_root and expected_root and code_root != expected_root:
+ state = EXTERNAL_STATE
if state == "unknown" and code_sha and expected_sha:
state = "current" if str(code_sha) == str(expected_sha) else "stale"
row = {
"profile": profile, "pid": pid, "code_sha": str(code_sha) if code_sha else None,
"code_version": code_version, "state": state,
+ "code_root": str(code_root) if code_root else None,
}
# A live, identity-verified multiplexer represents every profile in this
# list. Keep the field only when its shape is usable: callers use it to
@@ -340,6 +408,7 @@ def collect_fleet_versions(*, pre_restart_pids: Optional[list[int]] = None) -> l
_pre_restart = {int(p) for p in (pre_restart_pids or []) if isinstance(p, int)}
results: list[dict[str, Any]] = []
expected_sha = _code_identity(refresh=True).get("sha")
+ expected_root = _updater_code_root()
try:
from gateway.status import (
live_gateway_pid_for_home,
@@ -354,6 +423,7 @@ def collect_fleet_versions(*, pre_restart_pids: Optional[list[int]] = None) -> l
row = _fleet_row(
profile, pid, identity.get("code_sha"), identity.get("code_version"), expected_sha,
served_profiles=identity.get("served_profiles"),
+ code_root=_gateway_code_root(pid, home), expected_root=expected_root,
)
results.append({**row, "source": "socket"})
continue
@@ -372,6 +442,7 @@ def collect_fleet_versions(*, pre_restart_pids: Optional[list[int]] = None) -> l
_fleet_row(
profile, pid, record.get("code_sha"), record.get("code_version"), expected_sha,
served_profiles=record.get("served_profiles"),
+ code_root=_gateway_code_root(pid, home), expected_root=expected_root,
)
)
continue
@@ -402,6 +473,7 @@ _FLEET_ROW_LINES = {
"current": " ✓ {profile} (pid {pid}) @ {short} — up to date",
"stale": " ✗ {profile} (pid {pid}) @ {short} — STALE (pre-update code)",
"down": " ✗ {profile} — DOWN (gateway was running before the update; pid {pid} is gone and nothing replaced it)",
+ "external": " ◆ {profile} (pid {pid}) @ {short} — separate checkout, not updated by this run",
}
_FLEET_ROW_UNKNOWN = " ? {profile} (pid {pid}) — version unknown (gateway predates version stamping; restart to enable)"
# A gateway pid the pre-update snapshot did not know that had not published its code identity when
@@ -428,13 +500,21 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
print()
print("Fleet version check:")
states = set()
+ external_roots: list[str] = []
for entry in fleet:
sha = entry.get("code_sha")
states.add(entry.get("state"))
+ if row_is_external(entry) and entry.get("code_root"):
+ external_roots.append(f"{entry.get('profile')}: {entry.get('code_root')}")
fallback = _FLEET_ROW_IDENTITY_PENDING if entry.get("identity_pending") else _FLEET_ROW_UNKNOWN
print(_FLEET_ROW_LINES.get(entry.get("state"), fallback).format(
profile=entry.get("profile"), pid=entry.get("pid"), short=sha[:8] if isinstance(sha, str) and sha else "?",
))
+ if external_roots:
+ print()
+ print(" ℹ These profiles run their own checkout and are updated separately:")
+ for line in external_roots:
+ print(f" {line}")
stale_or_down = sum(1 for entry in fleet if entry.get("state") in ("stale", "down"))
if stale_or_down:
print()
diff --git a/tests/hermes_cli/test_update_external_checkout.py b/tests/hermes_cli/test_update_external_checkout.py
new file mode 100644
index 00000000000..03de992626e
--- /dev/null
+++ b/tests/hermes_cli/test_update_external_checkout.py
@@ -0,0 +1,97 @@
+"""Regression coverage for separate-checkout gateways (#117449)."""
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from hermes_cli import update_cmd_fleet, update_receipt
+
+
+def _checkout(tmp_path: Path, name: str) -> Path:
+ root = tmp_path / name
+ module = root / "hermes_cli" / "main.py"
+ module.parent.mkdir(parents=True)
+ module.write_text("", encoding="utf-8")
+ return root
+
+
+def test_different_checkout_is_external_but_same_checkout_sha_skew_is_stale(tmp_path):
+ updated = _checkout(tmp_path, "updated")
+ separate = _checkout(tmp_path, "separate")
+
+ external = update_receipt._fleet_row(
+ "pinned", 1, "old", "1", "new",
+ code_root=separate, expected_root=updated, served_profiles=["pinned", "coder", "coder"],
+ )
+ stale = update_receipt._fleet_row(
+ "default", 2, "old", "1", "new",
+ code_root=updated, expected_root=updated,
+ )
+
+ assert external["state"] == "external"
+ assert external["served_profiles"] == ["pinned", "coder"]
+ assert stale["state"] == "stale"
+
+
+def test_unresolved_checkout_fails_closed_to_sha_comparison():
+ row = update_receipt._fleet_row("default", 1, "old", "1", "new")
+ assert row["state"] == "stale"
+
+
+def test_code_root_requires_absolute_path(tmp_path, monkeypatch):
+ _checkout(tmp_path, "updated")
+ monkeypatch.chdir(tmp_path / "updated")
+ assert update_receipt._code_root_for_path("-m") is None
+ assert update_receipt._code_root_for_path("hermes_cli/main.py") is None
+
+
+def test_gateway_root_uses_pid_guarded_status_argv(tmp_path, monkeypatch):
+ root = _checkout(tmp_path, "pinned")
+ monkeypatch.setattr(
+ "gateway.status.read_runtime_status",
+ lambda _path: {"pid": 42, "argv": [str(root / "hermes_cli" / "main.py")]},
+ )
+ assert update_receipt._gateway_code_root(42, tmp_path / "home") == root.resolve()
+
+
+def test_gateway_root_uses_virtualenv_when_module_path_is_absent(tmp_path, monkeypatch):
+ root = _checkout(tmp_path, "pinned")
+ venv = root / "venv"
+ monkeypatch.setattr("gateway.status.read_runtime_status", lambda _path: {"pid": 42, "argv": ["-m"]})
+ fake_process = SimpleNamespace(
+ environ=lambda: {"VIRTUAL_ENV": str(venv)},
+ exe=lambda: "/usr/bin/python",
+ cmdline=lambda: ["python", "-m", "hermes_cli.main"],
+ )
+ monkeypatch.setattr("psutil.Process", lambda _pid: fake_process)
+ assert update_receipt._gateway_code_root(42, tmp_path / "home") == root.resolve()
+
+
+def test_external_receipt_row_does_not_report_runtime_skew():
+ receipt = {"fleet": [{"profile": "pinned", "state": "external", "code_sha": "foreign"}]}
+ assert update_cmd_fleet._receipt_reports_stale_runtime(receipt, "updated") is False
+
+
+def test_external_gateway_does_not_block_pending_restart_discharge(monkeypatch):
+ rows = [
+ {"profile": "default", "state": "current", "code_sha": "updated"},
+ {
+ "profile": "pinned", "state": "external", "code_sha": "foreign",
+ "served_profiles": ["pinned", "coder"],
+ },
+ ]
+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda: rows)
+ owed = {("gateway", "default"), ("gateway", "pinned"), ("gateway", "coder")}
+ assert update_cmd_fleet._live_fleet_covers_receipt("updated", {}, owed) is True
+
+
+def test_external_gateway_does_not_fail_matrix(capsys):
+ failed = update_receipt.print_fleet_version_matrix([
+ {
+ "profile": "pinned", "pid": 42, "code_sha": "foreign",
+ "state": "external", "code_root": "/srv/hermes-pinned",
+ }
+ ])
+ output = capsys.readouterr().out
+ assert failed is False
+ assert "separate checkout" in output
+ assert "/srv/hermes-pinned" in output
\ No newline at end of file