The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): re-park dedupe keys on the park line, so a new reason warns again
teknium1dc17eb0eb5ac
diff --git a/tests/gateway/test_housekeeping_profile_scope.py b/tests/gateway/test_housekeeping_profile_scope.pynew file mode 100644index 00000000000..32d7f5b25bb--- /dev/null+++ b/tests/gateway/test_housekeeping_profile_scope.py@@ -0,0 +1,113 @@+"""Housekeeping chores that read a profile's home, config or credentials run under the OWNING+profile's runtime scope on a multiplexed gateway.++The housekeeping thread has no turn on the stack, so nothing bound a profile for it: under+``gateway.multiplex_profiles`` the skills-sync pulls resolved Nous credentials through the+fail-closed reader and logged ``no profile secret scope on a multiplexed call`` four times per+hourly tick, per chore, while the launch profile's home/credentials leaked into every served+profile's pull. The MCP config reconciler already iterated the served profiles under+``_profile_runtime_scope``; the sync/curator ticks now ride the same iteration.+"""++import json+import logging+from pathlib import Path+from types import SimpleNamespace++import pytest++import gateway.run as gateway_run+++class _Ticks:+ """Stop event that lets the housekeeping loop run exactly ``n`` ticks with no sleeping."""++ def __init__(self, n: int):+ self.n, self.left = 0, n++ def is_set(self):+ return self.n >= self.left++ def wait(self, timeout=None):+ self.n += 1+ return True+++def _profile(home: Path, base_url: str) -> None:+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text("model:\n provider: nous\n", encoding="utf-8")+ (home / ".env").write_text(f"NOUS_INFERENCE_BASE_URL={base_url}\n", encoding="utf-8")+ (home / "auth.json").write_text(json.dumps({"version": 1, "providers": {"nous": {+ "access_token": "x.y.z", "refresh_token": "r", "expires_at": 0,+ "portal_base_url": "https://portal.nousresearch.com", "client_id": "c"}}}), encoding="utf-8")+++def two_homes(tmp_path, monkeypatch):+ """Launch home A (= multiplex ``default``) and served named profile B under ``A/profiles/b``."""+ fake_home = tmp_path / "home"+ a = fake_home / ".hermes"+ b = a / "profiles" / "b"+ _profile(a, "https://a.example/v1")+ _profile(b, "https://b.example/v1")+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: fake_home))+ monkeypatch.setenv("HERMES_HOME", str(a))+ monkeypatch.delenv("NOUS_INFERENCE_BASE_URL", raising=False)+ return a, b+++def _record_credential_chores(monkeypatch):+ """Replace the three credential-reading chores with recorders of (home, Nous override) they see."""+ import agent.curator as curator+ import tools.skills_sync_client as ssc+ import tools.skills_sync_client_org as sso+ from hermes_cli.auth_nous import _nous_inference_env_override+ from hermes_constants import get_hermes_home++ seen: dict = {"sync": [], "org": [], "curator": []}++ def _rec(key):+ return lambda *a, **k: seen[key].append((get_hermes_home().name, _nous_inference_env_override()))++ monkeypatch.setattr(ssc, "maybe_pull_skills", _rec("sync"))+ monkeypatch.setattr(sso, "maybe_pull_org_skills", _rec("org"))+ monkeypatch.setattr(curator, "maybe_run_curator", _rec("curator"))+ return seen+++def _run_60_ticks(runner):+ gateway_run._start_gateway_housekeeping(_Ticks(60), interval=0, runner=runner)+++def test_multiplexed_sync_ticks_run_once_per_profile_in_its_own_scope(two_homes, monkeypatch, caplog):+ """Under multiplex every credential-reading chore visits each served profile inside ITS scope:+ A's tick reads A's override, B's reads B's (B never sees A's), and no fail-closed credential+ read fires the ``no profile secret scope`` warning. The ambient home is untouched afterwards."""+ from agent.secret_scope import set_multiplex_active+ from hermes_constants import get_hermes_home++ a, b = two_homes+ seen = _record_credential_chores(monkeypatch)+ set_multiplex_active(True)+ try:+ with caplog.at_level(logging.WARNING):+ _run_60_ticks(SimpleNamespace(config=SimpleNamespace(multiplex_profiles=True)))+ finally:+ set_multiplex_active(False)++ expected = [(a.name, "https://a.example/v1"), (b.name, "https://b.example/v1")]+ assert seen == {"sync": expected, "org": expected, "curator": expected}+ assert not [r for r in caplog.records if "no profile secret scope" in r.getMessage()]+ assert get_hermes_home() == a+++def test_single_profile_sync_ticks_run_once_against_the_process_home(two_homes, monkeypatch):+ """Control: a single-profile gateway (multiplex off) still runs each chore exactly once against+ the process home — the named profile directory on disk is not visited."""+ a, _b = two_homes+ seen = _record_credential_chores(monkeypatch)++ _run_60_ticks(SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False)))++ assert {k: [h for h, _ in v] for k, v in seen.items()} == {+ "sync": [a.name], "org": [a.name], "curator": [a.name]}diff --git a/tests/tools/test_mcp_park_log_dedupe.py b/tests/tools/test_mcp_park_log_dedupe.pyindex 46738000e58..bd4ed3aa51d 100644--- a/tests/tools/test_mcp_park_log_dedupe.py+++ b/tests/tools/test_mcp_park_log_dedupe.py@@ -138,13 +138,16 @@ def test_park_after_revival_warns_again(monkeypatch, tmp_path, caplog):assert [r.levelno >= logging.WARNING for r in reconnect_parks] == [True, False]-def test_log_park_first_warns_repeat_debugs(caplog):+def test_park_for_a_different_reason_warns_again(caplog):+ """The dedupe is keyed on the park line, not on \"still parked\": a server parked on a+ connection error that re-parks on an auth error carries new information and warns again;+ only an identical repeat is demoted to DEBUG."""task = MCPServerTask("t")- task._was_parked = Falsewith caplog.at_level(logging.DEBUG, logger="tools.mcp_tool"):- task._log_park("first park of %s", "t")- assert caplog.records[-1].levelno == logging.WARNING- caplog.clear()- task._was_parked = True- task._log_park("repeat park of %s", "t")- assert caplog.records[-1].levelno == logging.DEBUG+ task._log_park("MCP server '%s' parked: %s", "t", "ConnectionError: refused")+ task._was_parked = True # _park() latches this on the first park+ task._log_park("MCP server '%s' parked: %s", "t", "ConnectionError: refused")+ task._log_park("MCP server '%s' parked: %s", "t", "OAuthError: token revoked")+ task._log_park("MCP server '%s' parked: %s", "t", "OAuthError: token revoked")+ assert [r.levelno for r in caplog.records] == [+ logging.WARNING, logging.DEBUG, logging.WARNING, logging.DEBUG]diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex b4abae11ef9..d97a9d0e6de 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -317,7 +317,7 @@ class MCPServerTask(MCPServerRunMixin, MCPServerTransportMixin, MCPServerHealthM"_recycled_reason", "initialize_result", "_ping_unsupported", "_list_cache_meta","_reconnect_retries", "_session_proven", "_was_parked", "_inflight_tasks", "_reconnecting","_suspect_reason", "_teardown_race", "_permanent_grace_used", "_stdio_child_pids",- "_ever_connected", "_sse_fallback", "_park_reason")+ "_ever_connected", "_sse_fallback", "_park_reason", "_last_park_line")def __init__(self, name: str):self.name = name@@ -357,6 +357,7 @@ class MCPServerTask(MCPServerRunMixin, MCPServerTransportMixin, MCPServerHealthM# Lets cron preflight tell a network-blip park (recovering) from a permanent-error park# (revoked credentials, dead endpoint) that must not run the job tool-less forever.self._park_reason: Optional[str] = None+ self._last_park_line: Optional[str] = None # last park WARNING text; identical re-parks log at DEBUG# In-flight RPC tasks so a deliberate teardown fails them fast; _reconnecting is True# during that teardown so _track_inflight_rpc turns the cancel into a retryable error.# In-flight RPC bookkeeping (#48069 salvage): user-visible requests registered while running so adiff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 0b58c15008b..d38ad72c7c6 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -174,11 +174,15 @@ class MCPServerRunMixin:"""Park chatter control (#115713): re-parking a server that never revived is not a statetransition — ``hermes mcp list`` already surfaces the parked state, so one identicalWARNING per self-probe carries no new information. The first park (and the revived line- in ``_mark_session_proven``) stays a WARNING; repeats while still parked are demoted to- DEBUG so a long-lived gateway's error log is not flooded (10k+ identical lines/month)."""- if self._was_parked:+ in ``_mark_session_proven``) stays a WARNING; an identical repeat while still parked is+ demoted to DEBUG so a long-lived gateway's error log is not flooded (10k+ identical+ lines/month). A park for a DIFFERENT reason (auth error after connection refused) is new+ information and warns again."""+ line = msg % args if args else msg+ if self._was_parked and line == self._last_park_line:logger.debug(msg, *args)else:+ self._last_park_line = linelogger.warning(msg, *args)async def _park(self, revival_reason: str) -> bool: