The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): attribute scoped credential lock conflicts to the owning profile (OOF-3)
Shannon Sandsc127d0c3b11f
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex a85b7b42aca..242e29f5cdc 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3526,6 +3526,7 @@ class BasePlatformAdapter(ABC):"""from gateway.status import (acquire_scoped_lock,+ scoped_lock_owner_label,take_over_scoped_lock_holder,)@@ -3573,11 +3574,21 @@ class BasePlatformAdapter(ABC):return Trueowner_pid = existing.get('pid') if isinstance(existing, dict) else None- message = (- f'{resource_desc} already in use'- + (f' (PID {owner_pid})' if owner_pid else '')- + '. Stop the other gateway first.'- )+ # OOF-3: scoped locks are machine-global, so the holder can be a+ # different profile's gateway. A bare PID gives an operator no way to+ # tell WHICH profile owns the credential — name it when we can.+ owner_profile = scoped_lock_owner_label(existing)+ if owner_profile:+ holder = f" by the '{owner_profile}' profile gateway"+ holder += f" (PID {owner_pid})" if owner_pid else ""+ remedy = (+ f" Stop that gateway first "+ f"(hermes --profile {owner_profile} gateway stop)."+ )+ else:+ holder = f" (PID {owner_pid})" if owner_pid else ""+ remedy = " Stop the other gateway first."+ message = f"{resource_desc} already in use{holder}.{remedy}"logger.error('[%s] %s', self.name, message)self._set_fatal_error(f'{scope}_lock', message, retryable=True)return Falsediff --git a/gateway/status.py b/gateway/status.pyindex 1616d109342..8f4d5fcad8c 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -16,6 +16,7 @@ import hashlibimport jsonimport loggingimport os+import reimport shleximport signalimport subprocess@@ -156,6 +157,63 @@ def _same_hermes_home(left: Path | str, right: Path | str) -> bool:)+# Mirrors hermes_cli.profiles._PROFILE_ID_RE — duplicated here because gateway+# identity code must stay import-light (hermes_constants + stdlib only).+_PROFILE_LABEL_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")+++def _profile_label_for_home(home: Path | str) -> Optional[str]:+ """Best-effort profile label for a HERMES_HOME path.++ Returns the profile name for ``<root>/profiles/<name>`` layouts (both+ ``~/.hermes/profiles/coder`` and Docker ``/opt/data/profiles/coder``),+ ``"default"`` for the deployment's root home, and ``None`` when no label+ can be inferred. Never raises — this feeds diagnostics only.+ """+ try:+ canonical = _canonical_hermes_home(home)+ except Exception:+ return None+ if canonical.parent.name == "profiles" and _PROFILE_LABEL_RE.match(canonical.name):+ return canonical.name+ try:+ from hermes_constants import get_default_hermes_root++ if _same_hermes_home(canonical, get_default_hermes_root()):+ return "default"+ except Exception:+ pass+ try:+ if _same_hermes_home(canonical, _get_platform_default_hermes_home()):+ return "default"+ except Exception:+ pass+ return None+++def scoped_lock_owner_label(record: Optional[dict[str, Any]]) -> Optional[str]:+ """Profile label for the gateway that owns a scoped credential lock.++ Scoped locks are machine-global, so the holder may belong to a different+ HERMES_HOME profile than the caller. Prefers the explicit ``profile``+ field stamped by :func:`acquire_scoped_lock`; falls back to inferring the+ label from the persisted ``hermes_home`` for locks written before the+ profile field existed. Returns ``None`` for legacy or malformed records+ so callers keep their PID-only wording.+ """+ if not isinstance(record, dict):+ return None+ profile = record.get("profile")+ if isinstance(profile, str) and _PROFILE_LABEL_RE.match(profile.strip()):+ # Validate the persisted label — lock files are plain JSON on disk,+ # and this string flows into log lines and a suggested CLI command.+ return profile.strip()+ home = record.get("hermes_home")+ if isinstance(home, str) and home.strip():+ return _profile_label_for_home(home)+ return None++def _get_pid_path() -> Path:"""Return the path to the gateway PID file, respecting HERMES_HOME."""home = _get_process_hermes_home()@@ -1387,6 +1445,15 @@ def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str,"metadata": metadata or {},"updated_at": _utc_now_iso(),}+ # Human-readable profile label for cross-profile conflict diagnostics+ # (OOF-3): "Telegram bot token already in use (PID 559)" gives an+ # operator no way to tell WHICH profile owns the credential. Stamped+ # only on scoped-lock records (they're machine-global; PID/runtime+ # status files are per-home and don't need it). Omitted when no label+ # is inferable; readers fall back to deriving it from hermes_home.+ profile = _profile_label_for_home(_get_process_hermes_home())+ if profile:+ record["profile"] = profileexisting = _read_json_file(lock_path)if existing is None and lock_path.exists():diff --git a/tests/gateway/test_stale_platform_lock_retryable.py b/tests/gateway/test_stale_platform_lock_retryable.pyindex 43aca8931e7..f4cb68a9985 100644--- a/tests/gateway/test_stale_platform_lock_retryable.py+++ b/tests/gateway/test_stale_platform_lock_retryable.py@@ -106,3 +106,79 @@ def test_explicit_replace_takeover_reacquires_lock_once(adapter):assert acquire.call_count == 2+def test_lock_conflict_names_owning_profile(adapter):+ """OOF-3: cross-profile conflicts must name the owning profile, not just a PID."""+ existing = {+ "pid": 559,+ "start_time": 123,+ "profile": "lead-gen-outreach",+ "hermes_home": "/opt/data/profiles/lead-gen-outreach",+ }++ with patch(+ "gateway.status.acquire_scoped_lock",+ return_value=(False, existing),+ ), patch.object(adapter, "_write_runtime_status_safe"):+ result = adapter._acquire_platform_lock(+ "telegram-bot-token",+ "test-token",+ "Telegram bot token",+ )++ assert result is False+ assert adapter._fatal_error_message == (+ "Telegram bot token already in use by the "+ "'lead-gen-outreach' profile gateway (PID 559). "+ "Stop that gateway first "+ "(hermes --profile lead-gen-outreach gateway stop)."+ )+ assert adapter._fatal_error_retryable is True+ assert adapter._fatal_error_code == "telegram-bot-token_lock"+++def test_lock_conflict_infers_profile_from_legacy_hermes_home(adapter):+ """Locks written before the profile field existed still attribute via hermes_home."""+ existing = {+ "pid": 559,+ "start_time": 123,+ "hermes_home": "/opt/data/profiles/lead-gen-outreach",+ }++ with patch(+ "gateway.status.acquire_scoped_lock",+ return_value=(False, existing),+ ), patch.object(adapter, "_write_runtime_status_safe"):+ result = adapter._acquire_platform_lock(+ "telegram-bot-token",+ "test-token",+ "Telegram bot token",+ )++ assert result is False+ assert "'lead-gen-outreach' profile gateway (PID 559)" in (+ adapter._fatal_error_message+ )+++def test_lock_conflict_keeps_pid_only_wording_for_legacy_record(adapter):+ """Records with no attribution signal retain the original PID-only message."""+ existing = {+ "pid": 99999,+ "start_time": 123,+ }++ with patch(+ "gateway.status.acquire_scoped_lock",+ return_value=(False, existing),+ ), patch.object(adapter, "_write_runtime_status_safe"):+ result = adapter._acquire_platform_lock(+ "telegram-bot-token",+ "test-token",+ "Telegram bot token",+ )++ assert result is False+ assert adapter._fatal_error_message == (+ "Telegram bot token already in use (PID 99999). "+ "Stop the other gateway first."+ )diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex eea8e05a0a4..9e5e7f78430 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -603,6 +603,95 @@ class TestScopedLocks:assert not target_lock.exists()assert other_lock.exists()+ def test_acquire_scoped_lock_stamps_profile_label(self, tmp_path, monkeypatch):+ """OOF-3: scoped locks are machine-global — record which profile owns them."""+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "lead-gen-outreach"))++ acquired, existing = status.acquire_scoped_lock(+ "telegram-bot-token", "secret", metadata={"platform": "telegram"}+ )++ assert acquired is True+ lock_path = tmp_path / "locks" / (+ "telegram-bot-token-" + status._scope_hash("secret") + ".lock"+ )+ payload = json.loads(lock_path.read_text())+ assert payload["profile"] == "lead-gen-outreach"++ def test_acquire_scoped_lock_omits_profile_when_not_inferable(self, tmp_path, monkeypatch):+ """No label for unrecognizable custom homes — field omitted, not null."""+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "some-custom-dir"))+ monkeypatch.setattr(status, "_profile_label_for_home", lambda home: None)++ acquired, _ = status.acquire_scoped_lock("telegram-bot-token", "secret")++ assert acquired is True+ lock_path = tmp_path / "locks" / (+ "telegram-bot-token-" + status._scope_hash("secret") + ".lock"+ )+ payload = json.loads(lock_path.read_text())+ assert "profile" not in payload+++class TestScopedLockOwnerLabel:+ """OOF-3: attribute a machine-global credential lock to its owning profile."""++ def test_profile_label_for_named_profile_home(self, tmp_path):+ home = tmp_path / "profiles" / "lead-gen-outreach"+ assert status._profile_label_for_home(home) == "lead-gen-outreach"++ def test_profile_label_for_docker_profile_home(self):+ assert (+ status._profile_label_for_home("/opt/data/profiles/zerocool")+ == "zerocool"+ )++ def test_profile_label_for_root_home_is_default(self, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", "/opt/data")+ assert status._profile_label_for_home("/opt/data") == "default"++ def test_profile_label_for_unknown_layout_is_none(self, monkeypatch):+ monkeypatch.delenv("HERMES_HOME", raising=False)+ assert status._profile_label_for_home("/somewhere/else") is None++ def test_profile_label_rejects_invalid_directory_names(self, tmp_path):+ # Directory names outside the profile-id grammar must not be+ # reported as profiles (they flow into a suggested CLI command).+ home = tmp_path / "profiles" / "Bad Name!"+ assert status._profile_label_for_home(home) is None++ def test_owner_label_prefers_explicit_profile_field(self):+ record = {"profile": "coder", "hermes_home": "/opt/data/profiles/other"}+ assert status.scoped_lock_owner_label(record) == "coder"++ def test_owner_label_rejects_malformed_profile_field(self):+ # Lock files are plain JSON on disk — a tampered/corrupt profile+ # string must never reach log lines or CLI guidance.+ assert status.scoped_lock_owner_label({"profile": "Bad Name!"}) is None+ assert status.scoped_lock_owner_label({"profile": " "}) is None+ assert status.scoped_lock_owner_label({"profile": 42}) is None++ def test_owner_label_ignores_invalid_profile_and_uses_home(self):+ # An invalid persisted profile string must not block the safe+ # hermes_home fallback — attribution degrades, never corrupts.+ record = {+ "profile": "bad; rm -rf /",+ "hermes_home": "/opt/data/profiles/zerocool",+ }+ assert status.scoped_lock_owner_label(record) == "zerocool"++ def test_owner_label_falls_back_to_hermes_home(self):+ # Locks written before the profile field existed still attribute.+ record = {"pid": 559, "hermes_home": "/opt/data/profiles/zerocool"}+ assert status.scoped_lock_owner_label(record) == "zerocool"++ def test_owner_label_none_for_legacy_and_malformed_records(self):+ assert status.scoped_lock_owner_label({"pid": 99999}) is None+ assert status.scoped_lock_owner_label(None) is None+ assert status.scoped_lock_owner_label("not-a-dict") is None+class TestTakeoverMarker:"""Tests for the --replace takeover marker.