The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: split oversized test files into topical siblings
Teknium3ccb8e6c0f1a
diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex 039f82ec1a0..511ba84c609 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -2617,53 +2617,3 @@ class TestBuildJobPromptExtraPrompt:job = {"prompt": "original"}_build_job_prompt(job, extra_prompt="transient context")assert job["prompt"] == "original"--class TestSetCronSessionTitle:- """Robust cron session titling: #50535/#50536/#50537."""-- def test_dedupes_on_duplicate_title(self):- # First write collides (ValueError); helper falls back to lineage #N.- from cron.scheduler import _set_cron_session_title- db = MagicMock()- db.set_session_title.side_effect = [ValueError("in use"), True]- db.get_next_title_in_lineage.return_value = "Nightly Synthesis #2"- out = _set_cron_session_title(db, "sess-1", "Nightly Synthesis")- assert out == "Nightly Synthesis #2"- db.get_next_title_in_lineage.assert_called_once_with("Nightly Synthesis")--class TestFailureStreakNudge:- """Poke-inspired repeated-failure review nudge (_failure_streak_nudge)."""-- def _job(self, streak, kind="cron", name="scout"):- return {- "id": "j1",- "name": name,- "failure_streak": streak,- "schedule": {"kind": kind},- }-- def test_silent_below_threshold(self):- from cron.scheduler import _failure_streak_nudge- with patch("cron.scheduler.load_config", return_value={}):- assert _failure_streak_nudge(self._job(0)) == ""- assert _failure_streak_nudge(self._job(1)) == ""-- def test_oneshot_never_nudges(self):- from cron.scheduler import _failure_streak_nudge- with patch("cron.scheduler.load_config", return_value={}):- assert _failure_streak_nudge(self._job(10, kind="once")) == ""-- def test_config_threshold_and_disable(self):- from cron.scheduler import _failure_streak_nudge- cfg5 = {"cron": {"failure_nudge_threshold": 5}}- with patch("cron.scheduler.load_config", return_value=cfg5):- assert _failure_streak_nudge(self._job(3)) == ""- assert _failure_streak_nudge(self._job(4))- with patch("cron.scheduler.load_config", return_value={"cron": {"failure_nudge_threshold": 0}}):- assert _failure_streak_nudge(self._job(50)) == ""-- def test_missing_streak_field_backcompat(self):- from cron.scheduler import _failure_streak_nudge- job = {"id": "old", "schedule": {"kind": "interval"}} # pre-field job- with patch("cron.scheduler.load_config", return_value={}):- assert _failure_streak_nudge(job) == ""diff --git a/tests/cron/test_scheduler_session_title_nudge.py b/tests/cron/test_scheduler_session_title_nudge.pynew file mode 100644index 00000000000..98a3c822105--- /dev/null+++ b/tests/cron/test_scheduler_session_title_nudge.py@@ -0,0 +1,54 @@+"""Tests for cron/scheduler.py — cron session titling and the repeated-failure review nudge."""++from unittest.mock import MagicMock, patch+++class TestSetCronSessionTitle:+ """Robust cron session titling: #50535/#50536/#50537."""++ def test_dedupes_on_duplicate_title(self):+ # First write collides (ValueError); helper falls back to lineage #N.+ from cron.scheduler import _set_cron_session_title+ db = MagicMock()+ db.set_session_title.side_effect = [ValueError("in use"), True]+ db.get_next_title_in_lineage.return_value = "Nightly Synthesis #2"+ out = _set_cron_session_title(db, "sess-1", "Nightly Synthesis")+ assert out == "Nightly Synthesis #2"+ db.get_next_title_in_lineage.assert_called_once_with("Nightly Synthesis")++class TestFailureStreakNudge:+ """Poke-inspired repeated-failure review nudge (_failure_streak_nudge)."""++ def _job(self, streak, kind="cron", name="scout"):+ return {+ "id": "j1",+ "name": name,+ "failure_streak": streak,+ "schedule": {"kind": kind},+ }++ def test_silent_below_threshold(self):+ from cron.scheduler import _failure_streak_nudge+ with patch("cron.scheduler.load_config", return_value={}):+ assert _failure_streak_nudge(self._job(0)) == ""+ assert _failure_streak_nudge(self._job(1)) == ""++ def test_oneshot_never_nudges(self):+ from cron.scheduler import _failure_streak_nudge+ with patch("cron.scheduler.load_config", return_value={}):+ assert _failure_streak_nudge(self._job(10, kind="once")) == ""++ def test_config_threshold_and_disable(self):+ from cron.scheduler import _failure_streak_nudge+ cfg5 = {"cron": {"failure_nudge_threshold": 5}}+ with patch("cron.scheduler.load_config", return_value=cfg5):+ assert _failure_streak_nudge(self._job(3)) == ""+ assert _failure_streak_nudge(self._job(4))+ with patch("cron.scheduler.load_config", return_value={"cron": {"failure_nudge_threshold": 0}}):+ assert _failure_streak_nudge(self._job(50)) == ""++ def test_missing_streak_field_backcompat(self):+ from cron.scheduler import _failure_streak_nudge+ job = {"id": "old", "schedule": {"kind": "interval"}} # pre-field job+ with patch("cron.scheduler.load_config", return_value={}):+ assert _failure_streak_nudge(job) == ""diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 86d307b4da6..ddf9e6968d1 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -29,7 +29,6 @@ from gateway.platforms.api_server import (cors_middleware,security_headers_middleware,)-from gateway.platforms.api_server_runs import _RunStreamfrom tools import approval as approval_modfrom tools import approval_gateway_wait@@ -1973,733 +1972,6 @@ class TestRunIdempotency:assert "run_old" not in adapter._run_owners--class TestHostedRoomRuns:- @pytest.mark.asyncio- async def test_room_approval_requires_and_resolves_exact_request_id(- self, auth_adapter- ):- run_id = "run-room-approval"- current = approval_gateway_wait._ApprovalEntry({- "request_id": "approval-B",- "command": "rm -rf build-B",- })- auth_adapter._run_approval_sessions[run_id] = run_id- auth_adapter._run_statuses[run_id] = {- "run_id": run_id,- "status": "waiting_for_approval",- "approval": dict(current.data),- }- with approval_mod._lock:- approval_mod._gateway_queues[run_id] = [current]- app = _create_runs_app(auth_adapter)- try:- with (- patch.object(auth_adapter, "_check_run_auth", return_value=None),- patch.object(auth_adapter, "_request_owns_run", return_value=True),- patch.object(- auth_adapter, "_room_grant_token", return_value="scoped-grant"- ),- ):- async with TestClient(TestServer(app)) as cli:- missing = await cli.post(- f"/v1/runs/{run_id}/approval",- json={"choice": "once"},- )- stale = await cli.post(- f"/v1/runs/{run_id}/approval",- json={"choice": "once", "request_id": "approval-A"},- )- exact = await cli.post(- f"/v1/runs/{run_id}/approval",- json={"choice": "once", "request_id": "approval-B"},- )- missing_body = await missing.json()- stale_body = await stale.json()- exact_body = await exact.json()- finally:- approval_mod.unregister_gateway_notify(run_id)-- assert missing.status == 400- assert missing_body["error"]["code"] == "approval_request_required"- assert stale.status == 409- assert stale_body["error"]["code"] == "approval_not_pending"- assert exact.status == 200- assert exact_body["request_id"] == "approval-B"- assert current.result == "once"- assert "approval" not in auth_adapter._run_statuses[run_id]-- @pytest.mark.asyncio- async def test_room_grant_cannot_create_session_or_permanent_approval_policy(- self, auth_adapter- ):- app = _create_runs_app(auth_adapter)- with (- patch.object(auth_adapter, "_check_run_auth", return_value=None),- patch.object(auth_adapter, "_request_owns_run", return_value=True),- patch.object(- auth_adapter,- "_durable_run_status",- return_value={"status": "waiting_for_approval"},- ),- patch.object(- auth_adapter, "_room_grant_token", return_value="scoped-grant"- ),- ):- async with TestClient(TestServer(app)) as cli:- permanent = await cli.post(- "/v1/runs/run-room/approval",- json={"choice": "always"},- )- resolve_all = await cli.post(- "/v1/runs/run-room/approval",- json={"choice": "once", "resolve_all": True},- )- permanent_body = await permanent.json()- resolve_all_body = await resolve_all.json()-- assert permanent.status == 400- assert permanent_body["error"]["code"] == "invalid_approval_choice"- assert resolve_all.status == 400- assert resolve_all_body["error"]["code"] == "invalid_approval_scope"-- @pytest.mark.asyncio- async def test_invitation_uses_validated_app_managed_local_catalog(- self, auth_adapter, monkeypatch- ):- monkeypatch.setenv("HERMES_DESKTOP", "1")- monkeypatch.setenv(- "HERMES_ROOM_LINK_URL", "https://peer.example.test/hermes"- )- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- },- headers={"Authorization": "Bearer sk-secret"},- )- body = await invitation.json()- assert invitation.status == 201- assert body["catalog"]["persistent_process"] is False- assert body["catalog"]["link_modes"] == ["direct"]- assert body["catalog"]["endpoint"] == {- "available": True,- "url": "https://peer.example.test/hermes",- "transport_security": "tls",- }- assert body["expires_at"] == body["status_expires_at"]-- @pytest.mark.asyncio- async def test_invitation_returns_operator_selected_status_horizon(- self, auth_adapter- ):- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "room_id": "room-horizon",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- "ttl_seconds": 600,- "status_ttl_seconds": 3600,- },- headers={"Authorization": "Bearer sk-secret"},- )- body = await invitation.json()-- assert invitation.status == 201- assert body["status_expires_at"] - body["expires_at"] == 3000-- @pytest.mark.asyncio- async def test_scoped_grant_refresh_requires_live_dispatch_authority(- self, auth_adapter, monkeypatch- ):- from gateway import hosted_rooms- from gateway.hosted_room_peer import decode_room_grant, issue_room_grant- from gateway.hosted_rooms import local_authority_gateway_id-- old_grant = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-old",- room_id="room-1",- home_install_id="install-home",- authority_gateway_id="install-home",- authority_epoch=1,- member_id="member-peer",- target_install_id=local_authority_gateway_id(),- target_profile="default",- issued_at=100,- ttl_seconds=300,- status_expires_at=1000,- )- old_claims = decode_room_grant(- auth_adapter._room_grant_secret(),- old_grant,- permission="status",- now=100,- )- hosted_rooms.reserve_peer_room(- hosted_rooms.default_db_path(),- claims=old_claims,- expires_at=1000,- now=100,- )- monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- refreshed = await cli.post(- "/v1/room-members/grants/refresh",- json={"ttl_seconds": 300},- headers={"Authorization": f"HermesRoom {old_grant}"},- )- body = await refreshed.json()- assert refreshed.status == 200- assert body["grant"] != old_grant- claims = decode_room_grant(- auth_adapter._room_grant_secret(),- body["grant"],- permission="dispatch",- now=200,- )- assert claims["room_id"] == "room-1"- assert claims["home_install_id"] == "install-home"- assert claims["status_expires_at"] == 1000-- status_only = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-status-only",- room_id="room-1",- home_install_id="install-home",- authority_gateway_id="install-home",- authority_epoch=1,- member_id="member-peer",- target_install_id=local_authority_gateway_id(),- target_profile="default",- permissions=("status",),- issued_at=100,- ttl_seconds=300,- status_expires_at=1000,- )- status_claims = decode_room_grant(- auth_adapter._room_grant_secret(),- status_only,- permission="status",- now=100,- )- hosted_rooms.reserve_peer_room(- hosted_rooms.default_db_path(),- claims=status_claims,- expires_at=1000,- now=100,- )- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- status_refresh = await cli.post(- "/v1/room-members/grants/refresh",- json={"ttl_seconds": 300},- headers={"Authorization": f"HermesRoom {status_only}"},- )- status_refresh_body = await status_refresh.json()- assert status_refresh.status == 401- assert status_refresh_body["error"]["code"] == "invalid_room_grant"-- fully_expired = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-expired",- room_id="room-1",- home_install_id="install-home",- authority_gateway_id="install-home",- authority_epoch=1,- member_id="member-peer",- target_install_id=local_authority_gateway_id(),- target_profile="default",- issued_at=100,- ttl_seconds=10,- status_expires_at=150,- )- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- denied = await cli.post(- "/v1/room-members/grants/refresh",- json={},- headers={"Authorization": f"HermesRoom {fully_expired}"},- )- denied_body = await denied.json()- assert denied.status == 401- assert denied_body["error"]["code"] == "invalid_room_grant"-- @pytest.mark.asyncio- async def test_scoped_grant_refresh_refuses_execution_policy_drift(- self, auth_adapter, monkeypatch- ):- """Renewal must pause for reauthorization when the target's execution- policy changed since the grant was issued — never silently mint a- grant against the drifted policy (blocker 2, #97681 review)."""- from gateway import hosted_rooms- from gateway.hosted_room_peer import issue_room_grant, decode_room_grant- from gateway.hosted_rooms import local_authority_gateway_id-- stale_digest = "c" * 64- drifted = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-drifted",- room_id="room-1",- home_install_id="install-home",- authority_gateway_id="install-home",- authority_epoch=1,- member_id="member-peer",- target_install_id=local_authority_gateway_id(),- target_profile="default",- execution_policy_digest=stale_digest,- issued_at=100,- ttl_seconds=300,- status_expires_at=1000,- )- drifted_claims = decode_room_grant(- auth_adapter._room_grant_secret(),- drifted,- permission="status",- now=100,- )- hosted_rooms.reserve_peer_room(- hosted_rooms.default_db_path(),- claims=drifted_claims,- expires_at=1000,- now=100,- )- monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- refused = await cli.post(- "/v1/room-members/grants/refresh",- json={"ttl_seconds": 300},- headers={"Authorization": f"HermesRoom {drifted}"},- )- refused_body = await refused.json()- assert refused.status == 403- assert refused_body["error"]["code"] == "room_reauthorization_required"-- @pytest.mark.asyncio- async def test_scoped_grant_refresh_fails_after_secret_rotation(- self, auth_adapter, monkeypatch- ):- from gateway.hosted_room_peer import issue_room_grant- from gateway.hosted_rooms import local_authority_gateway_id-- monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)- revoked = issue_room_grant(- b"x" * 32,- grant_id="grant-revoked",- room_id="room-1",- home_install_id="install-home",- authority_gateway_id="install-home",- authority_epoch=1,- member_id="member-peer",- target_install_id=local_authority_gateway_id(),- target_profile="default",- issued_at=100,- ttl_seconds=300,- status_expires_at=1000,- )- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- denied = await cli.post(- "/v1/room-members/grants/refresh",- json={},- headers={"Authorization": f"HermesRoom {revoked}"},- )- denied_body = await denied.json()- assert denied.status == 401- assert denied_body["error"]["code"] == "invalid_room_grant"-- def test_grant_refresh_keeps_idempotency_scope_but_member_change_does_not(- self, auth_adapter- ):- from types import SimpleNamespace-- from gateway import hosted_rooms- from gateway.hosted_room_peer import decode_room_grant, issue_room_grant- from gateway.hosted_rooms import local_authority_gateway_id-- common = {- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- "target_install_id": local_authority_gateway_id(),- "target_profile": "default",- }- first = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-first",- **common,- )- refreshed = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-refreshed",- **common,- )- other_member = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-other-member",- **{**common, "member_id": "member-other"},- )- for grant in (first, other_member):- claims = decode_room_grant(- auth_adapter._room_grant_secret(),- grant,- permission="status",- )- hosted_rooms.reserve_peer_room(- hosted_rooms.default_db_path(),- claims=claims,- expires_at=float(claims["status_expires_at"]),- )-- def request(token):- return SimpleNamespace(- headers={"Authorization": f"HermesRoom {token}"},- method="POST",- path="/v1/runs",- )-- first_scope = auth_adapter._run_idempotency_scope(request(first))- assert auth_adapter._run_idempotency_scope(request(refreshed)) == first_scope- assert auth_adapter._run_idempotency_scope(request(other_member)) != first_scope-- @pytest.mark.asyncio- async def test_scoped_grant_revoke_is_idempotent_and_fences_prior_lineage(- self, auth_adapter, monkeypatch- ):- from gateway import hosted_rooms- from gateway.hosted_room_peer import decode_room_grant, issue_room_grant- from gateway.hosted_rooms import local_authority_gateway_id-- for target in (- "gateway.platforms.api_server.time.time",- "gateway.hosted_rooms_common.time.time",- ):- monkeypatch.setattr(target, lambda: 200)- claims = {- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "install-home",- "authority_epoch": 1,- "member_id": "member-peer",- "target_install_id": local_authority_gateway_id(),- "target_profile": "default",- }- old_grant = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-old",- **claims,- issued_at=100,- ttl_seconds=300,- status_expires_at=1000,- )- app = _create_runs_app(auth_adapter)- async with TestClient(TestServer(app)) as cli:- first = await cli.post(- "/v1/room-members/grants/revoke",- json={},- headers={"Authorization": f"HermesRoom {old_grant}"},- )- repeated = await cli.post(- "/v1/room-members/grants/revoke",- json={},- headers={"Authorization": f"HermesRoom {old_grant}"},- )- denied = await cli.get(- "/v1/room-members/capabilities",- headers={"Authorization": f"HermesRoom {old_grant}"},- )- denied_run = await cli.post(- "/v1/runs",- data="{never parsed",- headers={- "Authorization": f"HermesRoom {old_grant}",- "Content-Type": "application/json",- },- )- denied_body = await denied.json()- denied_run_body = await denied_run.json()- future_grant = issue_room_grant(- auth_adapter._room_grant_secret(),- grant_id="grant-repaired",- **claims,- issued_at=201,- ttl_seconds=300,- status_expires_at=1000,- )- future_claims = decode_room_grant(- auth_adapter._room_grant_secret(),- future_grant,- permission="status",- now=201,- )- hosted_rooms.reserve_peer_room(- hosted_rooms.default_db_path(),- claims=future_claims,- expires_at=1000,- now=201,- )- repaired = await cli.get(- "/v1/room-members/capabilities",- headers={"Authorization": f"HermesRoom {future_grant}"},- )- assert first.status == repeated.status == 200- assert denied.status == 403- assert denied_body["error"]["code"] == "room_reauthorization_required"- assert denied_run.status == 403- assert (- denied_run_body["error"]["code"]- == "room_reauthorization_required"- )- assert auth_adapter._pending_agent_requests == 0- assert repaired.status == 200-- @pytest.mark.asyncio- async def test_status_room_grant_opens_the_run_event_stream(self, auth_adapter, tmp_path):- """A grant that may poll a room-scoped run may also read its /events stream, with no- gateway API key; revoking the grant closes that door again."""- adapter = auth_adapter- _use_idempotency_db(adapter, tmp_path / "idem.db")- app = _create_runs_app(adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- },- headers={"Authorization": "Bearer sk-secret"},- )- grant = (await invitation.json())["grant"]- room_headers = {"Authorization": f"HermesRoom {grant}"}- run_id = "run_room_stream"- scope_request = MagicMock()- scope_request.headers = room_headers- scope_request.path = f"/v1/runs/{run_id}/events"- scope_request.method = "GET"- adapter._run_owners[run_id] = adapter._run_idempotency_scope(scope_request)- adapter._run_streams[run_id] = _RunStream()- adapter._run_streams_created[run_id] = time.time()- adapter._set_run_status(run_id, "running")-- polled = await cli.get(f"/v1/runs/{run_id}", headers=room_headers)- assert polled.status == 200- stream = await cli.get(f"/v1/runs/{run_id}/events", headers=room_headers)- assert stream.status == 200- adapter._run_streams[run_id].put_nowait(None)- assert b"stream closed" in await asyncio.wait_for(stream.content.read(), timeout=5.0)-- revoked = await cli.post("/v1/room-members/grants/revoke", json={}, headers=room_headers)- assert revoked.status == 200- adapter._run_streams[run_id] = _RunStream()- denied = await cli.get(f"/v1/runs/{run_id}/events", headers=room_headers)- assert denied.status == 403- assert (await denied.json())["error"]["code"] == "room_reauthorization_required"-- @pytest.mark.asyncio- @pytest.mark.parametrize(- ("method", "suffix"),- [("GET", ""), ("POST", "/stop"), ("POST", "/resolve-unknown")],- )- async def test_room_grant_cannot_access_ownerless_compat_run(- self, auth_adapter, tmp_path, method, suffix- ):- adapter = auth_adapter- _use_idempotency_db(adapter, tmp_path / "idem.db")- app = _create_runs_app(adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- },- headers={"Authorization": "Bearer sk-secret"},- )- grant = (await invitation.json())["grant"]- adapter._run_statuses["run_ownerless"] = {- "run_id": "run_ownerless",- "status": "running",- }- response = await cli.request(- method,- f"/v1/runs/run_ownerless{suffix}",- json={} if method == "POST" else None,- headers={"Authorization": f"HermesRoom {grant}"},- )- assert response.status == 404-- @pytest.mark.asyncio- async def test_scoped_grant_admits_group_session_run_without_peer_api_key(- self, auth_adapter, tmp_path- ):- from gateway import hosted_rooms-- adapter = auth_adapter- _use_idempotency_db(adapter, tmp_path / "idem.db")- app = _create_runs_app(adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "grant_id": "grant-room-1",- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- "ttl_seconds": 3600,- },- headers={"Authorization": "Bearer sk-secret"},- )- invitation_body = await invitation.json()- assert invitation.status == 201- grant = invitation_body["grant"]- catalog = invitation_body["catalog"]- probe = await cli.get(- "/v1/room-members/capabilities",- headers={"Authorization": f"HermesRoom {grant}"},- )- probe_body = await probe.json()- assert probe.status == 200- assert probe_body["catalog"] == catalog- prompt = "Review this room message."- dispatch = {- "protocol_version": 2,- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- "target_install_id": catalog["installation_id"],- "target_profile": "default",- "task_id": "task-room-1",- "execution_generation": 1,- "source_event_seq": 1,- "cancellation_scope_id": "cancel-room-1",- "prompt": prompt,- "prompt_digest": hashlib.sha256(prompt.encode()).hexdigest(),- "capability_digest": catalog["catalog_digest"],- "execution_policy_digest": catalog["execution_policy"][- "policy_digest"- ],- "trace_id": "trace-room-1",- }- with patch.object(adapter, "_create_agent") as create:- agent = MagicMock()- agent.run_conversation.return_value = {- "final_response": "Scoped room reply."- }- agent.session_prompt_tokens = agent.session_completion_tokens = (- agent.session_total_tokens- ) = 0- create.return_value = agent- started = await cli.post(- "/v1/runs",- json={"input": prompt, "hosted_room_dispatch": dispatch},- headers={- "Authorization": f"HermesRoom {grant}",- "Idempotency-Key": "room:task-room-1:1",- },- )- started_body = await started.json()- assert started.status == 202- run_id = started_body["run_id"]- for _ in range(40):- status = await cli.get(- f"/v1/runs/{run_id}",- headers={"Authorization": f"HermesRoom {grant}"},- )- status_body = await status.json()- if status_body.get("status") == "completed":- break- await asyncio.sleep(0.05)- assert status.status == 200- assert status_body["output"] == "Scoped room reply."- session_id = status_body["session_id"]- db = await adapter._ensure_session_db_async()- row = db.get_session(session_id)- assert row["source"] == "bot_room"- assert row["title"] == "Group: room-1"- assert catalog["installation_id"] == (- hosted_rooms.local_authority_gateway_id()- )-- @pytest.mark.asyncio- async def test_scoped_grant_rejects_capability_and_target_tampering(- self, auth_adapter, tmp_path- ):- adapter = auth_adapter- _use_idempotency_db(adapter, tmp_path / "idem.db")- app = _create_runs_app(adapter)- async with TestClient(TestServer(app)) as cli:- invitation = await cli.post(- "/v1/room-members/invitations",- json={- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- },- headers={"Authorization": "Bearer sk-secret"},- )- invitation_body = await invitation.json()- prompt = "Review."- dispatch = {- "protocol_version": 2,- "room_id": "room-1",- "home_install_id": "install-home",- "authority_gateway_id": "gateway-home",- "authority_epoch": 1,- "member_id": "member-reviewer",- "target_install_id": invitation_body["catalog"]["installation_id"],- "target_profile": "default",- "task_id": "task-room-1",- "execution_generation": 1,- "source_event_seq": 1,- "cancellation_scope_id": "cancel-room-1",- "prompt": prompt,- "prompt_digest": hashlib.sha256(prompt.encode()).hexdigest(),- "capability_digest": "f" * 64,- "execution_policy_digest": invitation_body["catalog"][- "execution_policy"- ]["policy_digest"],- "trace_id": "trace-room-1",- }- with patch.object(adapter, "_create_agent") as create:- rejected = await cli.post(- "/v1/runs",- json={"input": prompt, "hosted_room_dispatch": dispatch},- headers={- "Authorization": f"HermesRoom {invitation_body['grant']}",- "Idempotency-Key": "room:task-room-1:1",- },- )- assert rejected.status == 403- create.assert_not_called()--class TestRunEventsHeadFlush:"""The SSE head must reach the client before the first event (#80757).diff --git a/tests/gateway/test_api_server_runs_hosted_room.py b/tests/gateway/test_api_server_runs_hosted_room.pynew file mode 100644index 00000000000..88d111104c9--- /dev/null+++ b/tests/gateway/test_api_server_runs_hosted_room.py@@ -0,0 +1,754 @@+"""Tests for /v1/runs under hosted-room grants (``HermesRoom`` authorization).++Covers room-member invitations/grants driving runs: exact approval request ids,+grant scope limits on approval policy, status/event-stream access, and refusals.+Shared app/adapter helpers live in ``tests/gateway/test_api_server_runs.py``.+"""++import asyncio+import hashlib+import time+from unittest.mock import MagicMock, patch++import pytest+from aiohttp.test_utils import TestClient, TestServer++from gateway.platforms.api_server_runs import _RunStream+from tests.gateway.test_api_server_runs import (+ _create_runs_app,+ _make_adapter,+ _use_idempotency_db,+)+from tools import approval as approval_mod+from tools import approval_gateway_wait+++def auth_adapter():+ return _make_adapter(api_key="sk-secret")+++class TestHostedRoomRuns:+ @pytest.mark.asyncio+ async def test_room_approval_requires_and_resolves_exact_request_id(+ self, auth_adapter+ ):+ run_id = "run-room-approval"+ current = approval_gateway_wait._ApprovalEntry({+ "request_id": "approval-B",+ "command": "rm -rf build-B",+ })+ auth_adapter._run_approval_sessions[run_id] = run_id+ auth_adapter._run_statuses[run_id] = {+ "run_id": run_id,+ "status": "waiting_for_approval",+ "approval": dict(current.data),+ }+ with approval_mod._lock:+ approval_mod._gateway_queues[run_id] = [current]+ app = _create_runs_app(auth_adapter)+ try:+ with (+ patch.object(auth_adapter, "_check_run_auth", return_value=None),+ patch.object(auth_adapter, "_request_owns_run", return_value=True),+ patch.object(+ auth_adapter, "_room_grant_token", return_value="scoped-grant"+ ),+ ):+ async with TestClient(TestServer(app)) as cli:+ missing = await cli.post(+ f"/v1/runs/{run_id}/approval",+ json={"choice": "once"},+ )+ stale = await cli.post(+ f"/v1/runs/{run_id}/approval",+ json={"choice": "once", "request_id": "approval-A"},+ )+ exact = await cli.post(+ f"/v1/runs/{run_id}/approval",+ json={"choice": "once", "request_id": "approval-B"},+ )+ missing_body = await missing.json()+ stale_body = await stale.json()+ exact_body = await exact.json()+ finally:+ approval_mod.unregister_gateway_notify(run_id)++ assert missing.status == 400+ assert missing_body["error"]["code"] == "approval_request_required"+ assert stale.status == 409+ assert stale_body["error"]["code"] == "approval_not_pending"+ assert exact.status == 200+ assert exact_body["request_id"] == "approval-B"+ assert current.result == "once"+ assert "approval" not in auth_adapter._run_statuses[run_id]++ @pytest.mark.asyncio+ async def test_room_grant_cannot_create_session_or_permanent_approval_policy(+ self, auth_adapter+ ):+ app = _create_runs_app(auth_adapter)+ with (+ patch.object(auth_adapter, "_check_run_auth", return_value=None),+ patch.object(auth_adapter, "_request_owns_run", return_value=True),+ patch.object(+ auth_adapter,+ "_durable_run_status",+ return_value={"status": "waiting_for_approval"},+ ),+ patch.object(+ auth_adapter, "_room_grant_token", return_value="scoped-grant"+ ),+ ):+ async with TestClient(TestServer(app)) as cli:+ permanent = await cli.post(+ "/v1/runs/run-room/approval",+ json={"choice": "always"},+ )+ resolve_all = await cli.post(+ "/v1/runs/run-room/approval",+ json={"choice": "once", "resolve_all": True},+ )+ permanent_body = await permanent.json()+ resolve_all_body = await resolve_all.json()++ assert permanent.status == 400+ assert permanent_body["error"]["code"] == "invalid_approval_choice"+ assert resolve_all.status == 400+ assert resolve_all_body["error"]["code"] == "invalid_approval_scope"++ @pytest.mark.asyncio+ async def test_invitation_uses_validated_app_managed_local_catalog(+ self, auth_adapter, monkeypatch+ ):+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ monkeypatch.setenv(+ "HERMES_ROOM_LINK_URL", "https://peer.example.test/hermes"+ )+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ body = await invitation.json()+ assert invitation.status == 201+ assert body["catalog"]["persistent_process"] is False+ assert body["catalog"]["link_modes"] == ["direct"]+ assert body["catalog"]["endpoint"] == {+ "available": True,+ "url": "https://peer.example.test/hermes",+ "transport_security": "tls",+ }+ assert body["expires_at"] == body["status_expires_at"]++ @pytest.mark.asyncio+ async def test_invitation_returns_operator_selected_status_horizon(+ self, auth_adapter+ ):+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "room_id": "room-horizon",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ "ttl_seconds": 600,+ "status_ttl_seconds": 3600,+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ body = await invitation.json()++ assert invitation.status == 201+ assert body["status_expires_at"] - body["expires_at"] == 3000++ @pytest.mark.asyncio+ async def test_scoped_grant_refresh_requires_live_dispatch_authority(+ self, auth_adapter, monkeypatch+ ):+ from gateway import hosted_rooms+ from gateway.hosted_room_peer import decode_room_grant, issue_room_grant+ from gateway.hosted_rooms import local_authority_gateway_id++ old_grant = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-old",+ room_id="room-1",+ home_install_id="install-home",+ authority_gateway_id="install-home",+ authority_epoch=1,+ member_id="member-peer",+ target_install_id=local_authority_gateway_id(),+ target_profile="default",+ issued_at=100,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ old_claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ old_grant,+ permission="status",+ now=100,+ )+ hosted_rooms.reserve_peer_room(+ hosted_rooms.default_db_path(),+ claims=old_claims,+ expires_at=1000,+ now=100,+ )+ monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ refreshed = await cli.post(+ "/v1/room-members/grants/refresh",+ json={"ttl_seconds": 300},+ headers={"Authorization": f"HermesRoom {old_grant}"},+ )+ body = await refreshed.json()+ assert refreshed.status == 200+ assert body["grant"] != old_grant+ claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ body["grant"],+ permission="dispatch",+ now=200,+ )+ assert claims["room_id"] == "room-1"+ assert claims["home_install_id"] == "install-home"+ assert claims["status_expires_at"] == 1000++ status_only = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-status-only",+ room_id="room-1",+ home_install_id="install-home",+ authority_gateway_id="install-home",+ authority_epoch=1,+ member_id="member-peer",+ target_install_id=local_authority_gateway_id(),+ target_profile="default",+ permissions=("status",),+ issued_at=100,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ status_claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ status_only,+ permission="status",+ now=100,+ )+ hosted_rooms.reserve_peer_room(+ hosted_rooms.default_db_path(),+ claims=status_claims,+ expires_at=1000,+ now=100,+ )+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ status_refresh = await cli.post(+ "/v1/room-members/grants/refresh",+ json={"ttl_seconds": 300},+ headers={"Authorization": f"HermesRoom {status_only}"},+ )+ status_refresh_body = await status_refresh.json()+ assert status_refresh.status == 401+ assert status_refresh_body["error"]["code"] == "invalid_room_grant"++ fully_expired = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-expired",+ room_id="room-1",+ home_install_id="install-home",+ authority_gateway_id="install-home",+ authority_epoch=1,+ member_id="member-peer",+ target_install_id=local_authority_gateway_id(),+ target_profile="default",+ issued_at=100,+ ttl_seconds=10,+ status_expires_at=150,+ )+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ denied = await cli.post(+ "/v1/room-members/grants/refresh",+ json={},+ headers={"Authorization": f"HermesRoom {fully_expired}"},+ )+ denied_body = await denied.json()+ assert denied.status == 401+ assert denied_body["error"]["code"] == "invalid_room_grant"++ @pytest.mark.asyncio+ async def test_scoped_grant_refresh_refuses_execution_policy_drift(+ self, auth_adapter, monkeypatch+ ):+ """Renewal must pause for reauthorization when the target's execution+ policy changed since the grant was issued — never silently mint a+ grant against the drifted policy (blocker 2, #97681 review)."""+ from gateway import hosted_rooms+ from gateway.hosted_room_peer import issue_room_grant, decode_room_grant+ from gateway.hosted_rooms import local_authority_gateway_id++ stale_digest = "c" * 64+ drifted = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-drifted",+ room_id="room-1",+ home_install_id="install-home",+ authority_gateway_id="install-home",+ authority_epoch=1,+ member_id="member-peer",+ target_install_id=local_authority_gateway_id(),+ target_profile="default",+ execution_policy_digest=stale_digest,+ issued_at=100,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ drifted_claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ drifted,+ permission="status",+ now=100,+ )+ hosted_rooms.reserve_peer_room(+ hosted_rooms.default_db_path(),+ claims=drifted_claims,+ expires_at=1000,+ now=100,+ )+ monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ refused = await cli.post(+ "/v1/room-members/grants/refresh",+ json={"ttl_seconds": 300},+ headers={"Authorization": f"HermesRoom {drifted}"},+ )+ refused_body = await refused.json()+ assert refused.status == 403+ assert refused_body["error"]["code"] == "room_reauthorization_required"++ @pytest.mark.asyncio+ async def test_scoped_grant_refresh_fails_after_secret_rotation(+ self, auth_adapter, monkeypatch+ ):+ from gateway.hosted_room_peer import issue_room_grant+ from gateway.hosted_rooms import local_authority_gateway_id++ monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)+ revoked = issue_room_grant(+ b"x" * 32,+ grant_id="grant-revoked",+ room_id="room-1",+ home_install_id="install-home",+ authority_gateway_id="install-home",+ authority_epoch=1,+ member_id="member-peer",+ target_install_id=local_authority_gateway_id(),+ target_profile="default",+ issued_at=100,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ denied = await cli.post(+ "/v1/room-members/grants/refresh",+ json={},+ headers={"Authorization": f"HermesRoom {revoked}"},+ )+ denied_body = await denied.json()+ assert denied.status == 401+ assert denied_body["error"]["code"] == "invalid_room_grant"++ def test_grant_refresh_keeps_idempotency_scope_but_member_change_does_not(+ self, auth_adapter+ ):+ from types import SimpleNamespace++ from gateway import hosted_rooms+ from gateway.hosted_room_peer import decode_room_grant, issue_room_grant+ from gateway.hosted_rooms import local_authority_gateway_id++ common = {+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ "target_install_id": local_authority_gateway_id(),+ "target_profile": "default",+ }+ first = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-first",+ **common,+ )+ refreshed = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-refreshed",+ **common,+ )+ other_member = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-other-member",+ **{**common, "member_id": "member-other"},+ )+ for grant in (first, other_member):+ claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ grant,+ permission="status",+ )+ hosted_rooms.reserve_peer_room(+ hosted_rooms.default_db_path(),+ claims=claims,+ expires_at=float(claims["status_expires_at"]),+ )++ def request(token):+ return SimpleNamespace(+ headers={"Authorization": f"HermesRoom {token}"},+ method="POST",+ path="/v1/runs",+ )++ first_scope = auth_adapter._run_idempotency_scope(request(first))+ assert auth_adapter._run_idempotency_scope(request(refreshed)) == first_scope+ assert auth_adapter._run_idempotency_scope(request(other_member)) != first_scope++ @pytest.mark.asyncio+ async def test_scoped_grant_revoke_is_idempotent_and_fences_prior_lineage(+ self, auth_adapter, monkeypatch+ ):+ from gateway import hosted_rooms+ from gateway.hosted_room_peer import decode_room_grant, issue_room_grant+ from gateway.hosted_rooms import local_authority_gateway_id++ for target in (+ "gateway.platforms.api_server.time.time",+ "gateway.hosted_rooms_common.time.time",+ ):+ monkeypatch.setattr(target, lambda: 200)+ claims = {+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "install-home",+ "authority_epoch": 1,+ "member_id": "member-peer",+ "target_install_id": local_authority_gateway_id(),+ "target_profile": "default",+ }+ old_grant = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-old",+ **claims,+ issued_at=100,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ app = _create_runs_app(auth_adapter)+ async with TestClient(TestServer(app)) as cli:+ first = await cli.post(+ "/v1/room-members/grants/revoke",+ json={},+ headers={"Authorization": f"HermesRoom {old_grant}"},+ )+ repeated = await cli.post(+ "/v1/room-members/grants/revoke",+ json={},+ headers={"Authorization": f"HermesRoom {old_grant}"},+ )+ denied = await cli.get(+ "/v1/room-members/capabilities",+ headers={"Authorization": f"HermesRoom {old_grant}"},+ )+ denied_run = await cli.post(+ "/v1/runs",+ data="{never parsed",+ headers={+ "Authorization": f"HermesRoom {old_grant}",+ "Content-Type": "application/json",+ },+ )+ denied_body = await denied.json()+ denied_run_body = await denied_run.json()+ future_grant = issue_room_grant(+ auth_adapter._room_grant_secret(),+ grant_id="grant-repaired",+ **claims,+ issued_at=201,+ ttl_seconds=300,+ status_expires_at=1000,+ )+ future_claims = decode_room_grant(+ auth_adapter._room_grant_secret(),+ future_grant,+ permission="status",+ now=201,+ )+ hosted_rooms.reserve_peer_room(+ hosted_rooms.default_db_path(),+ claims=future_claims,+ expires_at=1000,+ now=201,+ )+ repaired = await cli.get(+ "/v1/room-members/capabilities",+ headers={"Authorization": f"HermesRoom {future_grant}"},+ )+ assert first.status == repeated.status == 200+ assert denied.status == 403+ assert denied_body["error"]["code"] == "room_reauthorization_required"+ assert denied_run.status == 403+ assert (+ denied_run_body["error"]["code"]+ == "room_reauthorization_required"+ )+ assert auth_adapter._pending_agent_requests == 0+ assert repaired.status == 200++ @pytest.mark.asyncio+ async def test_status_room_grant_opens_the_run_event_stream(self, auth_adapter, tmp_path):+ """A grant that may poll a room-scoped run may also read its /events stream, with no+ gateway API key; revoking the grant closes that door again."""+ adapter = auth_adapter+ _use_idempotency_db(adapter, tmp_path / "idem.db")+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ grant = (await invitation.json())["grant"]+ room_headers = {"Authorization": f"HermesRoom {grant}"}+ run_id = "run_room_stream"+ scope_request = MagicMock()+ scope_request.headers = room_headers+ scope_request.path = f"/v1/runs/{run_id}/events"+ scope_request.method = "GET"+ adapter._run_owners[run_id] = adapter._run_idempotency_scope(scope_request)+ adapter._run_streams[run_id] = _RunStream()+ adapter._run_streams_created[run_id] = time.time()+ adapter._set_run_status(run_id, "running")++ polled = await cli.get(f"/v1/runs/{run_id}", headers=room_headers)+ assert polled.status == 200+ stream = await cli.get(f"/v1/runs/{run_id}/events", headers=room_headers)+ assert stream.status == 200+ adapter._run_streams[run_id].put_nowait(None)+ assert b"stream closed" in await asyncio.wait_for(stream.content.read(), timeout=5.0)++ revoked = await cli.post("/v1/room-members/grants/revoke", json={}, headers=room_headers)+ assert revoked.status == 200+ adapter._run_streams[run_id] = _RunStream()+ denied = await cli.get(f"/v1/runs/{run_id}/events", headers=room_headers)+ assert denied.status == 403+ assert (await denied.json())["error"]["code"] == "room_reauthorization_required"++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("method", "suffix"),+ [("GET", ""), ("POST", "/stop"), ("POST", "/resolve-unknown")],+ )+ async def test_room_grant_cannot_access_ownerless_compat_run(+ self, auth_adapter, tmp_path, method, suffix+ ):+ adapter = auth_adapter+ _use_idempotency_db(adapter, tmp_path / "idem.db")+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ grant = (await invitation.json())["grant"]+ adapter._run_statuses["run_ownerless"] = {+ "run_id": "run_ownerless",+ "status": "running",+ }+ response = await cli.request(+ method,+ f"/v1/runs/run_ownerless{suffix}",+ json={} if method == "POST" else None,+ headers={"Authorization": f"HermesRoom {grant}"},+ )+ assert response.status == 404++ @pytest.mark.asyncio+ async def test_scoped_grant_admits_group_session_run_without_peer_api_key(+ self, auth_adapter, tmp_path+ ):+ from gateway import hosted_rooms++ adapter = auth_adapter+ _use_idempotency_db(adapter, tmp_path / "idem.db")+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "grant_id": "grant-room-1",+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ "ttl_seconds": 3600,+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ invitation_body = await invitation.json()+ assert invitation.status == 201+ grant = invitation_body["grant"]+ catalog = invitation_body["catalog"]+ probe = await cli.get(+ "/v1/room-members/capabilities",+ headers={"Authorization": f"HermesRoom {grant}"},+ )+ probe_body = await probe.json()+ assert probe.status == 200+ assert probe_body["catalog"] == catalog+ prompt = "Review this room message."+ dispatch = {+ "protocol_version": 2,+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ "target_install_id": catalog["installation_id"],+ "target_profile": "default",+ "task_id": "task-room-1",+ "execution_generation": 1,+ "source_event_seq": 1,+ "cancellation_scope_id": "cancel-room-1",+ "prompt": prompt,+ "prompt_digest": hashlib.sha256(prompt.encode()).hexdigest(),+ "capability_digest": catalog["catalog_digest"],+ "execution_policy_digest": catalog["execution_policy"][+ "policy_digest"+ ],+ "trace_id": "trace-room-1",+ }+ with patch.object(adapter, "_create_agent") as create:+ agent = MagicMock()+ agent.run_conversation.return_value = {+ "final_response": "Scoped room reply."+ }+ agent.session_prompt_tokens = agent.session_completion_tokens = (+ agent.session_total_tokens+ ) = 0+ create.return_value = agent+ started = await cli.post(+ "/v1/runs",+ json={"input": prompt, "hosted_room_dispatch": dispatch},+ headers={+ "Authorization": f"HermesRoom {grant}",+ "Idempotency-Key": "room:task-room-1:1",+ },+ )+ started_body = await started.json()+ assert started.status == 202+ run_id = started_body["run_id"]+ for _ in range(40):+ status = await cli.get(+ f"/v1/runs/{run_id}",+ headers={"Authorization": f"HermesRoom {grant}"},+ )+ status_body = await status.json()+ if status_body.get("status") == "completed":+ break+ await asyncio.sleep(0.05)+ assert status.status == 200+ assert status_body["output"] == "Scoped room reply."+ session_id = status_body["session_id"]+ db = await adapter._ensure_session_db_async()+ row = db.get_session(session_id)+ assert row["source"] == "bot_room"+ assert row["title"] == "Group: room-1"+ assert catalog["installation_id"] == (+ hosted_rooms.local_authority_gateway_id()+ )++ @pytest.mark.asyncio+ async def test_scoped_grant_rejects_capability_and_target_tampering(+ self, auth_adapter, tmp_path+ ):+ adapter = auth_adapter+ _use_idempotency_db(adapter, tmp_path / "idem.db")+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ invitation = await cli.post(+ "/v1/room-members/invitations",+ json={+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ },+ headers={"Authorization": "Bearer sk-secret"},+ )+ invitation_body = await invitation.json()+ prompt = "Review."+ dispatch = {+ "protocol_version": 2,+ "room_id": "room-1",+ "home_install_id": "install-home",+ "authority_gateway_id": "gateway-home",+ "authority_epoch": 1,+ "member_id": "member-reviewer",+ "target_install_id": invitation_body["catalog"]["installation_id"],+ "target_profile": "default",+ "task_id": "task-room-1",+ "execution_generation": 1,+ "source_event_seq": 1,+ "cancellation_scope_id": "cancel-room-1",+ "prompt": prompt,+ "prompt_digest": hashlib.sha256(prompt.encode()).hexdigest(),+ "capability_digest": "f" * 64,+ "execution_policy_digest": invitation_body["catalog"][+ "execution_policy"+ ]["policy_digest"],+ "trace_id": "trace-room-1",+ }+ with patch.object(adapter, "_create_agent") as create:+ rejected = await cli.post(+ "/v1/runs",+ json={"input": prompt, "hosted_room_dispatch": dispatch},+ headers={+ "Authorization": f"HermesRoom {invitation_body['grant']}",+ "Idempotency-Key": "room:task-room-1:1",+ },+ )+ assert rejected.status == 403+ create.assert_not_called()diff --git a/tests/gateway/test_slack.py b/tests/gateway/test_slack.pyindex ea0563f28a2..829977c8a7f 100644--- a/tests/gateway/test_slack.py+++ b/tests/gateway/test_slack.py@@ -5651,69 +5651,6 @@ class TestSlackAuthoredTextDeduplication:assert "Roll back" in payload-class TestAgentSessionsApiRouting:- """slack-sdk 3.44.0 Agent Sessions API (assistant_view deprecation Feb 2027).-- When the installed slack-sdk ships agents.sessions.* typed methods, status- and title calls route through them; older SDKs keep using the legacy- assistant.threads.* methods (compat bridge on Slack's side).- """-- def _adapter(self):- config = PlatformConfig(enabled=True, token="xoxb-fake-token")- a = SlackAdapter(config)- a._app = MagicMock()- a._app.client = AsyncMock()- return a-- @pytest.mark.asyncio- async def test_typing_uses_agent_sessions_when_supported(self):- _slack_mod._AGENT_SESSIONS_SUPPORTED = True- a = self._adapter()- a._app.client.agents_sessions_setStatus = AsyncMock()- a._app.client.assistant_threads_setStatus = AsyncMock()- await a.send_typing("C123", metadata={"thread_id": "parent_ts"})- a._app.client.agents_sessions_setStatus.assert_called_once_with(- channel_id="C123",- thread_ts="parent_ts",- status="is thinking...",- )- a._app.client.assistant_threads_setStatus.assert_not_called()--- @pytest.mark.asyncio- async def test_stop_typing_clears_via_agent_sessions(self):- _slack_mod._AGENT_SESSIONS_SUPPORTED = True- a = self._adapter()- a._app.client.agents_sessions_setStatus = AsyncMock()- a._app.client.assistant_threads_setStatus = AsyncMock()- await a.send_typing("C123", metadata={"thread_id": "parent_ts"})- a._app.client.agents_sessions_setStatus.reset_mock()- await a.stop_typing("C123", metadata={"thread_id": "parent_ts"})- a._app.client.agents_sessions_setStatus.assert_called_once_with(- channel_id="C123",- thread_ts="parent_ts",- status="",- )- a._app.client.assistant_threads_setStatus.assert_not_called()-- @pytest.mark.asyncio- async def test_thread_title_uses_agents_sessions_rename(self):- _slack_mod._AGENT_SESSIONS_SUPPORTED = True- a = self._adapter()- a.config.extra["assistant_thread_titles"] = True- a._app.client.agents_sessions_rename = AsyncMock()- a._app.client.assistant_threads_setTitle = AsyncMock()- await a._set_assistant_thread_title("D123", "171234.0001", "Summarize the incident")- a._app.client.agents_sessions_rename.assert_called_once_with(- channel_id="D123",- thread_ts="171234.0001",- title="Summarize the incident",- )- a._app.client.assistant_threads_setTitle.assert_not_called()---# ---------------------------------------------------------------------------# TestNonConversationalSubtypeAllowlist# ---------------------------------------------------------------------------diff --git a/tests/gateway/test_slack_agent_sessions_api.py b/tests/gateway/test_slack_agent_sessions_api.pynew file mode 100644index 00000000000..58a1bc76baf--- /dev/null+++ b/tests/gateway/test_slack_agent_sessions_api.py@@ -0,0 +1,80 @@+"""Slack adapter routing onto the slack-sdk Agent Sessions API (agents.sessions.*)."""++from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import PlatformConfig+from tests.gateway.test_slack import SlackAdapter, _slack_mod++[email protected](autouse=True)+def _pin_legacy_assistant_threads_api():+ """Pin the SDK capability probe to the legacy assistant.threads API and+ restore it afterwards, so tests that flip the cached flag on don't leak."""+ prev = _slack_mod._AGENT_SESSIONS_SUPPORTED+ _slack_mod._AGENT_SESSIONS_SUPPORTED = False+ yield+ _slack_mod._AGENT_SESSIONS_SUPPORTED = prev+++class TestAgentSessionsApiRouting:+ """slack-sdk 3.44.0 Agent Sessions API (assistant_view deprecation Feb 2027).++ When the installed slack-sdk ships agents.sessions.* typed methods, status+ and title calls route through them; older SDKs keep using the legacy+ assistant.threads.* methods (compat bridge on Slack's side).+ """++ def _adapter(self):+ config = PlatformConfig(enabled=True, token="xoxb-fake-token")+ a = SlackAdapter(config)+ a._app = MagicMock()+ a._app.client = AsyncMock()+ return a++ @pytest.mark.asyncio+ async def test_typing_uses_agent_sessions_when_supported(self):+ _slack_mod._AGENT_SESSIONS_SUPPORTED = True+ a = self._adapter()+ a._app.client.agents_sessions_setStatus = AsyncMock()+ a._app.client.assistant_threads_setStatus = AsyncMock()+ await a.send_typing("C123", metadata={"thread_id": "parent_ts"})+ a._app.client.agents_sessions_setStatus.assert_called_once_with(+ channel_id="C123",+ thread_ts="parent_ts",+ status="is thinking...",+ )+ a._app.client.assistant_threads_setStatus.assert_not_called()+++ @pytest.mark.asyncio+ async def test_stop_typing_clears_via_agent_sessions(self):+ _slack_mod._AGENT_SESSIONS_SUPPORTED = True+ a = self._adapter()+ a._app.client.agents_sessions_setStatus = AsyncMock()+ a._app.client.assistant_threads_setStatus = AsyncMock()+ await a.send_typing("C123", metadata={"thread_id": "parent_ts"})+ a._app.client.agents_sessions_setStatus.reset_mock()+ await a.stop_typing("C123", metadata={"thread_id": "parent_ts"})+ a._app.client.agents_sessions_setStatus.assert_called_once_with(+ channel_id="C123",+ thread_ts="parent_ts",+ status="",+ )+ a._app.client.assistant_threads_setStatus.assert_not_called()++ @pytest.mark.asyncio+ async def test_thread_title_uses_agents_sessions_rename(self):+ _slack_mod._AGENT_SESSIONS_SUPPORTED = True+ a = self._adapter()+ a.config.extra["assistant_thread_titles"] = True+ a._app.client.agents_sessions_rename = AsyncMock()+ a._app.client.assistant_threads_setTitle = AsyncMock()+ await a._set_assistant_thread_title("D123", "171234.0001", "Summarize the incident")+ a._app.client.agents_sessions_rename.assert_called_once_with(+ channel_id="D123",+ thread_ts="171234.0001",+ title="Summarize the incident",+ )+ a._app.client.assistant_threads_setTitle.assert_not_called()diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex cda483429fb..90d4368c29c 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -2820,60 +2820,3 @@ def _count_rows(db_path: Path) -> tuple[int, int]:)finally:conn.close()---def test_run_backup_prunes_older_default_named_zips_but_not_others(tmp_path, monkeypatch):- """Hourly `hermes backup` callers accumulated 150+ zips; --keep bounds the default-named- ones and leaves custom-named or foreign zips alone (#81317)."""- from argparse import Namespace- from hermes_cli import backup as backup_mod-- home = tmp_path / ".hermes"- home.mkdir()- (home / "config.yaml").write_text("model: x\n")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(Path, "home", lambda: tmp_path)- for i in range(4):- (tmp_path / f"hermes-backup-2026-01-0{i + 1}-000000.zip").write_bytes(b"old")- (tmp_path / "my-archive.zip").write_bytes(b"mine")-- backup_mod.run_backup(Namespace(output=None, keep=2))-- kept = sorted(p.name for p in tmp_path.glob("hermes-backup-*.zip"))- assert len(kept) == 2 and kept[0] == "hermes-backup-2026-01-04-000000.zip"- assert (tmp_path / "my-archive.zip").exists()---def test_import_restores_the_session_store_with_its_message_uids(tmp_path, monkeypatch):- """A backup ships state.db as a SQLite snapshot and an import puts it back byte-for-byte: the durable- message ids come back with the rows."""- from hermes_state import SessionDB-- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- _make_hermes_tree(hermes_home)- db = SessionDB(db_path=hermes_home / "state.db")- try:- db.create_session("s", "cli", model="m")- db.append_message(session_id="s", role="user", content="q")- db.append_message(session_id="s", role="assistant", content="a")- uids = [m["message_uid"] for m in db.get_messages_as_conversation("s")]- finally:- db.close()- assert len(uids) == 2 and all(len(u) == 32 for u in uids)-- monkeypatch.setenv("HERMES_HOME", str(hermes_home))- monkeypatch.setattr(Path, "home", lambda: tmp_path)- from hermes_cli.backup import run_backup, run_import-- out_zip = tmp_path / "backup.zip"- run_backup(Namespace(output=str(out_zip)))- for name in ("state.db", "state.db-wal", "state.db-shm"):- (hermes_home / name).unlink(missing_ok=True)- assert run_import(Namespace(zipfile=str(out_zip), force=True)) is None-- restored = SessionDB(db_path=hermes_home / "state.db")- try:- assert [m["message_uid"] for m in restored.get_messages_as_conversation("s")] == uids- finally:- restored.close()diff --git a/tests/hermes_cli/test_backup_retention_roundtrip.py b/tests/hermes_cli/test_backup_retention_roundtrip.pynew file mode 100644index 00000000000..e1c0c0ac7f4--- /dev/null+++ b/tests/hermes_cli/test_backup_retention_roundtrip.py@@ -0,0 +1,76 @@+"""Tests for hermes backup retention (--keep) and the session-store import round trip."""++from argparse import Namespace+from pathlib import Path++import pytest++import hermes_cli.gateway_setup_service as service_setup+from tests.hermes_cli.test_backup import _make_hermes_tree++[email protected](autouse=True)+def _no_real_gateway_service(monkeypatch):+ """run_import() may start an existing gateway service post-restore; tests must+ never touch the host's systemd/launchd."""+ import hermes_cli.gateway as gateway_mod++ monkeypatch.setattr(service_setup, "ensure_gateway_service", lambda **kw: False)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+++def test_run_backup_prunes_older_default_named_zips_but_not_others(tmp_path, monkeypatch):+ """Hourly `hermes backup` callers accumulated 150+ zips; --keep bounds the default-named+ ones and leaves custom-named or foreign zips alone (#81317)."""+ from argparse import Namespace+ from hermes_cli import backup as backup_mod++ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "config.yaml").write_text("model: x\n")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ for i in range(4):+ (tmp_path / f"hermes-backup-2026-01-0{i + 1}-000000.zip").write_bytes(b"old")+ (tmp_path / "my-archive.zip").write_bytes(b"mine")++ backup_mod.run_backup(Namespace(output=None, keep=2))++ kept = sorted(p.name for p in tmp_path.glob("hermes-backup-*.zip"))+ assert len(kept) == 2 and kept[0] == "hermes-backup-2026-01-04-000000.zip"+ assert (tmp_path / "my-archive.zip").exists()+++def test_import_restores_the_session_store_with_its_message_uids(tmp_path, monkeypatch):+ """A backup ships state.db as a SQLite snapshot and an import puts it back byte-for-byte: the durable+ message ids come back with the rows."""+ from hermes_state import SessionDB++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ _make_hermes_tree(hermes_home)+ db = SessionDB(db_path=hermes_home / "state.db")+ try:+ db.create_session("s", "cli", model="m")+ db.append_message(session_id="s", role="user", content="q")+ db.append_message(session_id="s", role="assistant", content="a")+ uids = [m["message_uid"] for m in db.get_messages_as_conversation("s")]+ finally:+ db.close()+ assert len(uids) == 2 and all(len(u) == 32 for u in uids)++ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ from hermes_cli.backup import run_backup, run_import++ out_zip = tmp_path / "backup.zip"+ run_backup(Namespace(output=str(out_zip)))+ for name in ("state.db", "state.db-wal", "state.db-shm"):+ (hermes_home / name).unlink(missing_ok=True)+ assert run_import(Namespace(zipfile=str(out_zip), force=True)) is None++ restored = SessionDB(db_path=hermes_home / "state.db")+ try:+ assert [m["message_uid"] for m in restored.get_messages_as_conversation("s")] == uids+ finally:+ restored.close()diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 9801cd8dce2..a1598170f57 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -1002,65 +1002,6 @@ class TestConfigSupportFloor:assert (tmp_path / ".env").read_text(encoding="utf-8") == expected_env-class TestRetiredMultiplexAllowlist:- def test_v43_drops_multiplex_profile_allowlist_from_user_config(self, tmp_path, monkeypatch):- """The multiplexer serves every profile; a stale allowlist must not linger in config.yaml."""- from hermes_cli.config import DEFAULT_CONFIG- from hermes_cli.config_migrations import run_migrations-- config_path = tmp_path / "config.yaml"- config_path.write_text(yaml.safe_dump({- "_config_version": 42,- "gateway": {"multiplex_profiles": True, "multiplex_profile_allowlist": ["worker"]},- }), encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- run_migrations(42, {"env_added": [], "config_added": [], "warnings": []}, quiet=True)- raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert "multiplex_profile_allowlist" not in raw["gateway"]- assert raw["gateway"]["multiplex_profiles"] is True- assert "multiplex_profile_allowlist" not in DEFAULT_CONFIG["gateway"]---class TestCuratorFasterPrune:- def test_v44_rewrites_old_curator_defaults_but_keeps_user_values(self, tmp_path, monkeypatch):- """Old 30/90 defaults move to 14/30; an explicitly customized window is untouched."""- from hermes_cli.config import DEFAULT_CONFIG- from hermes_cli.config_migrations import run_migrations-- config_path = tmp_path / "config.yaml"- config_path.write_text(yaml.safe_dump({- "_config_version": 43,- "curator": {"stale_after_days": 30, "archive_after_days": 180},- }), encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- run_migrations(43, {"env_added": [], "config_added": [], "warnings": []}, quiet=True)- raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert raw["curator"]["stale_after_days"] == DEFAULT_CONFIG["curator"]["stale_after_days"]- assert raw["curator"]["archive_after_days"] == 180---class TestRetiredBotChatDeliveryTimeout:- def test_v51_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):- """The removed cron knob is dropped from existing configs with a one-time note;- sibling cron settings and the rest of the file survive untouched."""- from hermes_cli.config import DEFAULT_CONFIG- from hermes_cli.config_migrations import run_migrations-- config_path = tmp_path / "config.yaml"- config_path.write_text(yaml.safe_dump({- "_config_version": 50,- "cron": {"bot_chat_delivery_timeout_seconds": 900, "max_parallel_jobs": 2},- }), encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- results = {"env_added": [], "config_added": [], "warnings": []}- run_migrations(50, results, quiet=True)- raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))- assert "bot_chat_delivery_timeout_seconds" not in raw["cron"]- assert raw["cron"]["max_parallel_jobs"] == 2- assert any("bot_chat_delivery_timeout_seconds" in note for note in results["config_added"])- assert "bot_chat_delivery_timeout_seconds" not in DEFAULT_CONFIG["cron"]--class TestCustomProviderCompatibility:"""Custom provider compatibility across legacy and v12+ config schemas.diff --git a/tests/hermes_cli/test_config_retired_key_migrations.py b/tests/hermes_cli/test_config_retired_key_migrations.pynew file mode 100644index 00000000000..6b7f0cfc366--- /dev/null+++ b/tests/hermes_cli/test_config_retired_key_migrations.py@@ -0,0 +1,62 @@+"""Config migrations that retire or rewrite obsolete keys (v43 / v44 / v51)."""++import hermes_yaml as yaml+++class TestRetiredMultiplexAllowlist:+ def test_v43_drops_multiplex_profile_allowlist_from_user_config(self, tmp_path, monkeypatch):+ """The multiplexer serves every profile; a stale allowlist must not linger in config.yaml."""+ from hermes_cli.config import DEFAULT_CONFIG+ from hermes_cli.config_migrations import run_migrations++ config_path = tmp_path / "config.yaml"+ config_path.write_text(yaml.safe_dump({+ "_config_version": 42,+ "gateway": {"multiplex_profiles": True, "multiplex_profile_allowlist": ["worker"]},+ }), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ run_migrations(42, {"env_added": [], "config_added": [], "warnings": []}, quiet=True)+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert "multiplex_profile_allowlist" not in raw["gateway"]+ assert raw["gateway"]["multiplex_profiles"] is True+ assert "multiplex_profile_allowlist" not in DEFAULT_CONFIG["gateway"]+++class TestCuratorFasterPrune:+ def test_v44_rewrites_old_curator_defaults_but_keeps_user_values(self, tmp_path, monkeypatch):+ """Old 30/90 defaults move to 14/30; an explicitly customized window is untouched."""+ from hermes_cli.config import DEFAULT_CONFIG+ from hermes_cli.config_migrations import run_migrations++ config_path = tmp_path / "config.yaml"+ config_path.write_text(yaml.safe_dump({+ "_config_version": 43,+ "curator": {"stale_after_days": 30, "archive_after_days": 180},+ }), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ run_migrations(43, {"env_added": [], "config_added": [], "warnings": []}, quiet=True)+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert raw["curator"]["stale_after_days"] == DEFAULT_CONFIG["curator"]["stale_after_days"]+ assert raw["curator"]["archive_after_days"] == 180+++class TestRetiredBotChatDeliveryTimeout:+ def test_v51_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):+ """The removed cron knob is dropped from existing configs with a one-time note;+ sibling cron settings and the rest of the file survive untouched."""+ from hermes_cli.config import DEFAULT_CONFIG+ from hermes_cli.config_migrations import run_migrations++ config_path = tmp_path / "config.yaml"+ config_path.write_text(yaml.safe_dump({+ "_config_version": 50,+ "cron": {"bot_chat_delivery_timeout_seconds": 900, "max_parallel_jobs": 2},+ }), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ results = {"env_added": [], "config_added": [], "warnings": []}+ run_migrations(50, results, quiet=True)+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert "bot_chat_delivery_timeout_seconds" not in raw["cron"]+ assert raw["cron"]["max_parallel_jobs"] == 2+ assert any("bot_chat_delivery_timeout_seconds" in note for note in results["config_added"])+ assert "bot_chat_delivery_timeout_seconds" not in DEFAULT_CONFIG["cron"]diff --git a/tests/hermes_cli/test_runtime_provider_openai_runtime.py b/tests/hermes_cli/test_runtime_provider_openai_runtime.pynew file mode 100644index 00000000000..d818a8349d2--- /dev/null+++ b/tests/hermes_cli/test_runtime_provider_openai_runtime.py@@ -0,0 +1,108 @@+"""Runtime provider resolution: model.openai_runtime overlay, the ``openai`` alias, and launch keys."""++from types import SimpleNamespace++import pytest++from hermes_cli import runtime_provider as rp+++# ── model.openai_runtime: codex_app_server on every ladder rung (#115169) ─────────────────++_CODEX_STORE_CREDS = {"base_url": "https://chatgpt.com/backend-api/codex", "api_key": "tok",+ "source": "hermes-auth-store", "last_refresh": 1}+++def _codex_rung(monkeypatch, rung: str) -> dict:+ """Isolate one openai-codex ladder rung; returns the kwargs for resolve_runtime_provider."""+ monkeypatch.setattr(rp, "resolve_codex_runtime_credentials", lambda: dict(_CODEX_STORE_CREDS))+ if rung == "pool":+ entry = SimpleNamespace(api_key="tok", runtime_api_key="tok", base_url="", source="pool")+ monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(+ has_credentials=lambda: True, select=lambda model=None: entry))+ monkeypatch.setattr(rp, "credential_pool_matches_provider", lambda *a, **k: True)+ return {}+ monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(has_credentials=lambda: False))+ return {"explicit_api_key": "sk-explicit"} if rung == "explicit" else {}++[email protected]("rung", ["pool", "oauth", "explicit"])+def test_openai_runtime_codex_app_server_applies_on_every_rung(monkeypatch, rung):+ """#115169: the opt-in was applied only inside the credential-pool rung, so the OAuth-store+ and explicit --api-key/--base-url rungs silently resolved codex_responses."""+ kwargs = _codex_rung(monkeypatch, rung)+ monkeypatch.setattr(rp, "_get_model_config", lambda: {+ "provider": "openai-codex", "default": "gpt-5.5", "openai_runtime": "codex_app_server"})++ resolved = rp.resolve_runtime_provider(requested="openai-codex", **kwargs)++ assert resolved["provider"] == "openai-codex"+ assert resolved["api_mode"] == "codex_app_server"++[email protected]("rung", ["pool", "oauth", "explicit"])[email protected]("openai_runtime", [None, "auto"])+def test_openai_runtime_unset_keeps_wire_api_mode(monkeypatch, rung, openai_runtime):+ kwargs = _codex_rung(monkeypatch, rung)+ model_cfg = {"provider": "openai-codex", "default": "gpt-5.5"}+ if openai_runtime is not None:+ model_cfg["openai_runtime"] = openai_runtime+ monkeypatch.setattr(rp, "_get_model_config", lambda: model_cfg)++ assert rp.resolve_runtime_provider(requested="openai-codex", **kwargs)["api_mode"] == "codex_responses"+++def test_openai_runtime_codex_app_server_survives_the_openai_to_custom_alias_expansion(monkeypatch):+ """``provider: openai`` expands to the anonymous ``custom`` runtime (#116055) before the overlay runs;+ the overlay must judge the name the user configured, or the documented ``openai`` opt-in is a silent no-op."""+ monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(has_credentials=lambda: False))+ monkeypatch.setattr(rp, "_get_model_config", lambda: {+ "provider": "openai", "default": "gpt-5.5-codex", "openai_runtime": "codex_app_server"})++ resolved = rp.resolve_runtime_provider(requested="openai", explicit_api_key="sk-explicit")++ assert resolved["provider"] == "custom" # the alias expansion itself is unchanged+ assert resolved["api_mode"] == "codex_app_server"+++# ── #116055: ``provider: openai`` means the same thing on both auxiliary paths ──────────────────++def test_openai_alias_resolves_identically_on_runtime_and_aux_client_paths(monkeypatch):+ """background_review/curator/MoA (resolve_runtime_provider) and compression/vision/title+ (_resolve_task_provider_model) must land on the same endpoint for the same aux block."""+ from agent import auxiliary_client as aux+ block = {"provider": "openai", "model": "review-model", "base_url": "https://gateway.example/v1", "api_key": "gw-key"}+ monkeypatch.setattr(aux, "_get_auxiliary_task_config", lambda task: block if task == "background_review" else {})+ monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom:mylocal", "default": "local-main"})++ aux_provider, aux_model, aux_base, aux_key, _ = aux._resolve_task_provider_model("background_review")+ runtime = rp.resolve_runtime_provider(requested=block["provider"], target_model=block["model"],+ explicit_api_key=block["api_key"], explicit_base_url=block["base_url"])++ assert (aux_provider, aux_base, aux_key) == ("custom", "https://gateway.example/v1", "gw-key")+ assert (runtime["provider"], runtime["base_url"], runtime["api_key"]) == (aux_provider, aux_base, aux_key)+++def test_openai_alias_without_base_url_pairs_openai_key_with_openai_base_url(monkeypatch):+ """No aux base_url: the alias lands on OPENAI_BASE_URL (the proxy the key was issued for) and the+ runtime path pairs OPENAI_API_KEY with it instead of sending a placeholder key to the proxy."""+ monkeypatch.setenv("OPENAI_BASE_URL", "https://llm-proxy.corp.example/v1")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-proxy-issued")+ monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom:mylocal", "default": "local-main"})++ runtime = rp.resolve_runtime_provider(requested="openai", target_model="gpt-x")++ assert (runtime["provider"], runtime["base_url"], runtime["api_key"]) == ("custom", "https://llm-proxy.corp.example/v1", "sk-proxy-issued")+++def test_bare_custom_explicit_launch_key_wins_over_custom_pool(monkeypatch):+ """R2-M1: on the bare-custom terminal rung a launch ``--api-key`` must not be replaced by a+ pooled credential for the same URL (named-custom and direct-alias already honour it)."""+ from hermes_cli.runtime_provider_backends import _resolve_openrouter_runtime++ monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom"})+ monkeypatch.setattr(rp, "_try_resolve_from_custom_pool", lambda *a, **k: {+ "provider": "custom", "base_url": "http://127.0.0.1:9/v1", "api_key": "sk-pooled", "source": "pool"})+ resolved = _resolve_openrouter_runtime(requested_provider="custom", explicit_api_key="sk-launch-explicit",+ explicit_base_url="http://127.0.0.1:9/v1")+ assert resolved["api_key"] == "sk-launch-explicit"diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.pyindex fe954e144f9..17f6b1b0fa8 100644--- a/tests/hermes_cli/test_runtime_provider_resolution.py+++ b/tests/hermes_cli/test_runtime_provider_resolution.py@@ -2279,104 +2279,3 @@ def test_configured_key_env_resolving_empty_is_logged(monkeypatch, caplog):assert rp.resolve_runtime_provider(requested="custom:local")["api_key"] == "no-key-required"hits = [r for r in caplog.records if "UNSET_LLM_KEY" in r.getMessage()]assert len(hits) == 1 and "scw" in hits[0].getMessage()---# ── model.openai_runtime: codex_app_server on every ladder rung (#115169) ─────────────────--_CODEX_STORE_CREDS = {"base_url": "https://chatgpt.com/backend-api/codex", "api_key": "tok",- "source": "hermes-auth-store", "last_refresh": 1}---def _codex_rung(monkeypatch, rung: str) -> dict:- """Isolate one openai-codex ladder rung; returns the kwargs for resolve_runtime_provider."""- monkeypatch.setattr(rp, "resolve_codex_runtime_credentials", lambda: dict(_CODEX_STORE_CREDS))- if rung == "pool":- entry = SimpleNamespace(api_key="tok", runtime_api_key="tok", base_url="", source="pool")- monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(- has_credentials=lambda: True, select=lambda model=None: entry))- monkeypatch.setattr(rp, "credential_pool_matches_provider", lambda *a, **k: True)- return {}- monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(has_credentials=lambda: False))- return {"explicit_api_key": "sk-explicit"} if rung == "explicit" else {}--[email protected]("rung", ["pool", "oauth", "explicit"])-def test_openai_runtime_codex_app_server_applies_on_every_rung(monkeypatch, rung):- """#115169: the opt-in was applied only inside the credential-pool rung, so the OAuth-store- and explicit --api-key/--base-url rungs silently resolved codex_responses."""- kwargs = _codex_rung(monkeypatch, rung)- monkeypatch.setattr(rp, "_get_model_config", lambda: {- "provider": "openai-codex", "default": "gpt-5.5", "openai_runtime": "codex_app_server"})-- resolved = rp.resolve_runtime_provider(requested="openai-codex", **kwargs)-- assert resolved["provider"] == "openai-codex"- assert resolved["api_mode"] == "codex_app_server"--[email protected]("rung", ["pool", "oauth", "explicit"])[email protected]("openai_runtime", [None, "auto"])-def test_openai_runtime_unset_keeps_wire_api_mode(monkeypatch, rung, openai_runtime):- kwargs = _codex_rung(monkeypatch, rung)- model_cfg = {"provider": "openai-codex", "default": "gpt-5.5"}- if openai_runtime is not None:- model_cfg["openai_runtime"] = openai_runtime- monkeypatch.setattr(rp, "_get_model_config", lambda: model_cfg)-- assert rp.resolve_runtime_provider(requested="openai-codex", **kwargs)["api_mode"] == "codex_responses"---def test_openai_runtime_codex_app_server_survives_the_openai_to_custom_alias_expansion(monkeypatch):- """``provider: openai`` expands to the anonymous ``custom`` runtime (#116055) before the overlay runs;- the overlay must judge the name the user configured, or the documented ``openai`` opt-in is a silent no-op."""- monkeypatch.setattr(rp, "load_pool", lambda _p: SimpleNamespace(has_credentials=lambda: False))- monkeypatch.setattr(rp, "_get_model_config", lambda: {- "provider": "openai", "default": "gpt-5.5-codex", "openai_runtime": "codex_app_server"})-- resolved = rp.resolve_runtime_provider(requested="openai", explicit_api_key="sk-explicit")-- assert resolved["provider"] == "custom" # the alias expansion itself is unchanged- assert resolved["api_mode"] == "codex_app_server"---# ── #116055: ``provider: openai`` means the same thing on both auxiliary paths ──────────────────--def test_openai_alias_resolves_identically_on_runtime_and_aux_client_paths(monkeypatch):- """background_review/curator/MoA (resolve_runtime_provider) and compression/vision/title- (_resolve_task_provider_model) must land on the same endpoint for the same aux block."""- from agent import auxiliary_client as aux- block = {"provider": "openai", "model": "review-model", "base_url": "https://gateway.example/v1", "api_key": "gw-key"}- monkeypatch.setattr(aux, "_get_auxiliary_task_config", lambda task: block if task == "background_review" else {})- monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom:mylocal", "default": "local-main"})-- aux_provider, aux_model, aux_base, aux_key, _ = aux._resolve_task_provider_model("background_review")- runtime = rp.resolve_runtime_provider(requested=block["provider"], target_model=block["model"],- explicit_api_key=block["api_key"], explicit_base_url=block["base_url"])-- assert (aux_provider, aux_base, aux_key) == ("custom", "https://gateway.example/v1", "gw-key")- assert (runtime["provider"], runtime["base_url"], runtime["api_key"]) == (aux_provider, aux_base, aux_key)---def test_openai_alias_without_base_url_pairs_openai_key_with_openai_base_url(monkeypatch):- """No aux base_url: the alias lands on OPENAI_BASE_URL (the proxy the key was issued for) and the- runtime path pairs OPENAI_API_KEY with it instead of sending a placeholder key to the proxy."""- monkeypatch.setenv("OPENAI_BASE_URL", "https://llm-proxy.corp.example/v1")- monkeypatch.setenv("OPENAI_API_KEY", "sk-proxy-issued")- monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom:mylocal", "default": "local-main"})-- runtime = rp.resolve_runtime_provider(requested="openai", target_model="gpt-x")-- assert (runtime["provider"], runtime["base_url"], runtime["api_key"]) == ("custom", "https://llm-proxy.corp.example/v1", "sk-proxy-issued")---def test_bare_custom_explicit_launch_key_wins_over_custom_pool(monkeypatch):- """R2-M1: on the bare-custom terminal rung a launch ``--api-key`` must not be replaced by a- pooled credential for the same URL (named-custom and direct-alias already honour it)."""- from hermes_cli.runtime_provider_backends import _resolve_openrouter_runtime-- monkeypatch.setattr(rp, "_get_model_config", lambda: {"provider": "custom"})- monkeypatch.setattr(rp, "_try_resolve_from_custom_pool", lambda *a, **k: {- "provider": "custom", "base_url": "http://127.0.0.1:9/v1", "api_key": "sk-pooled", "source": "pool"})- resolved = _resolve_openrouter_runtime(requested_provider="custom", explicit_api_key="sk-launch-explicit",- explicit_base_url="http://127.0.0.1:9/v1")- assert resolved["api_key"] == "sk-launch-explicit"diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex c17b9b3d497..7c75c5fc0c9 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -5912,133 +5912,3 @@ class TestSubmittedCustomEndpointSurvivesAssignment:assert applied["base_url"] == "https://api.anthropic.com"assert applied["api_mode"] == "anthropic_messages"assert applied["api_key"] == "submitted-key"----class TestNousRecommendedDefaultCostSafePolicy:- """Paid-tier Nous recommended default must never land on an Anthropic frontier- tier (Opus / Fable) — the user gets no opt-out before it pins their main model- (#51491). Regression tests from PR #51493."""-- def test_recommended_default_nous_paid_uses_curated_default(self, monkeypatch):- """A paid Nous user gets the cost-safe silent default from the list.-- With no preferred catalog label present in the curated list and no- Anthropic frontier entries, the first curated entry is selected.- """- import hermes_cli.models as models_mod- from hermes_cli.web_routers.models import get_recommended_default_model-- monkeypatch.setattr(models_mod, "get_curated_nous_model_ids", lambda: ["top/model", "other/model"])- import hermes_cli.models_pricing as mp- monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})- monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)- monkeypatch.setattr(- models_mod, "union_with_portal_paid_recommendations",- lambda ids, pricing, url: (ids, pricing),- )- # Keep the catalog preferred out of this list so we exercise the- # non-frontier fallback rather than the preferred-hit branch.- monkeypatch.setattr(- models_mod, "get_preferred_silent_default_model",- lambda provider="openrouter": "z-ai/glm-5.2",- )-- result = get_recommended_default_model(provider="nous")- assert result["provider"] == "nous"- assert result["model"] == "top/model"- assert result["free_tier"] is False-- @pytest.mark.parametrize(- "model_ordering, expected_model",- [- # Opus-first ordering (historical PR-branch catalog shape).- (- [- "anthropic/claude-opus-4.8",- "anthropic/claude-sonnet-5",- "anthropic/claude-haiku-4.5",- ],- "anthropic/claude-sonnet-5",- ),- # Fable-first ordering (current origin/main catalog shape).- (- [- "anthropic/claude-fable-5",- "anthropic/claude-opus-4.8",- "anthropic/claude-sonnet-5",- "anthropic/claude-haiku-4.5",- ],- "anthropic/claude-sonnet-5",- ),- # Preferred silent default present in the list always wins,- # independent of relative ordering / frontiers.- (- [- "anthropic/claude-fable-5",- "anthropic/claude-opus-4.8",- "z-ai/glm-5.2",- "anthropic/claude-sonnet-5",- ],- "z-ai/glm-5.2",- ),- ],- ids=["opus_first", "fable_first_main", "override_beats_ordering"],- )- def test_recommended_default_nous_paid_cost_safe_policy(- self, monkeypatch, model_ordering, expected_model,- ):- """Regression for PR #51493 maintainer feedback (Teknium + DavidMetcalfe).-- The interactive Nous recommended default must use the shared- cost-safe silent policy: preferred catalog label when present,- else first non-frontier (Opus / Fable) entry. Covers both the- current Fable-first catalog and a future Opus-first catalog.- """- import hermes_cli.models as models_mod- from hermes_cli.web_routers.models import get_recommended_default_model-- monkeypatch.setattr(- models_mod, "get_curated_nous_model_ids", lambda: list(model_ordering),- )- import hermes_cli.models_pricing as mp- monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})- monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)- monkeypatch.setattr(- models_mod, "union_with_portal_paid_recommendations",- lambda ids, pricing, url: (ids, pricing),- )- monkeypatch.setattr(- models_mod, "get_preferred_silent_default_model",- lambda provider="openrouter": "z-ai/glm-5.2",- )-- result = get_recommended_default_model(provider="nous")- assert result["provider"] == "nous"- assert result["model"] == expected_model- assert result["free_tier"] is False-- def test_recommended_default_nous_paid_falls_back_when_all_frontier(self, monkeypatch):- """If every curated entry is a frontier tier (Opus / Fable), fall- back to the head of the list so the picker is never empty."""- import hermes_cli.models as models_mod- from hermes_cli.web_routers.models import get_recommended_default_model-- monkeypatch.setattr(- models_mod, "get_curated_nous_model_ids",- lambda: ["anthropic/claude-fable-5", "anthropic/claude-opus-4.8"],- )- import hermes_cli.models_pricing as mp- monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})- monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)- monkeypatch.setattr(- models_mod, "union_with_portal_paid_recommendations",- lambda ids, pricing, url: (ids, pricing),- )- monkeypatch.setattr(- models_mod, "get_preferred_silent_default_model",- lambda provider="openrouter": "z-ai/glm-5.2",- )-- result = get_recommended_default_model(provider="nous")- assert result["model"] == "anthropic/claude-fable-5"diff --git a/tests/hermes_cli/test_web_server_nous_recommended_default.py b/tests/hermes_cli/test_web_server_nous_recommended_default.pynew file mode 100644index 00000000000..fe4a48cb8ea--- /dev/null+++ b/tests/hermes_cli/test_web_server_nous_recommended_default.py@@ -0,0 +1,132 @@+"""Dashboard recommended-default model: the paid-tier Nous cost-safe policy (#51491)."""++import pytest+++class TestNousRecommendedDefaultCostSafePolicy:+ """Paid-tier Nous recommended default must never land on an Anthropic frontier+ tier (Opus / Fable) — the user gets no opt-out before it pins their main model+ (#51491). Regression tests from PR #51493."""++ def test_recommended_default_nous_paid_uses_curated_default(self, monkeypatch):+ """A paid Nous user gets the cost-safe silent default from the list.++ With no preferred catalog label present in the curated list and no+ Anthropic frontier entries, the first curated entry is selected.+ """+ import hermes_cli.models as models_mod+ from hermes_cli.web_routers.models import get_recommended_default_model++ monkeypatch.setattr(models_mod, "get_curated_nous_model_ids", lambda: ["top/model", "other/model"])+ import hermes_cli.models_pricing as mp+ monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})+ monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)+ monkeypatch.setattr(+ models_mod, "union_with_portal_paid_recommendations",+ lambda ids, pricing, url: (ids, pricing),+ )+ # Keep the catalog preferred out of this list so we exercise the+ # non-frontier fallback rather than the preferred-hit branch.+ monkeypatch.setattr(+ models_mod, "get_preferred_silent_default_model",+ lambda provider="openrouter": "z-ai/glm-5.2",+ )++ result = get_recommended_default_model(provider="nous")+ assert result["provider"] == "nous"+ assert result["model"] == "top/model"+ assert result["free_tier"] is False++ @pytest.mark.parametrize(+ "model_ordering, expected_model",+ [+ # Opus-first ordering (historical PR-branch catalog shape).+ (+ [+ "anthropic/claude-opus-4.8",+ "anthropic/claude-sonnet-5",+ "anthropic/claude-haiku-4.5",+ ],+ "anthropic/claude-sonnet-5",+ ),+ # Fable-first ordering (current origin/main catalog shape).+ (+ [+ "anthropic/claude-fable-5",+ "anthropic/claude-opus-4.8",+ "anthropic/claude-sonnet-5",+ "anthropic/claude-haiku-4.5",+ ],+ "anthropic/claude-sonnet-5",+ ),+ # Preferred silent default present in the list always wins,+ # independent of relative ordering / frontiers.+ (+ [+ "anthropic/claude-fable-5",+ "anthropic/claude-opus-4.8",+ "z-ai/glm-5.2",+ "anthropic/claude-sonnet-5",+ ],+ "z-ai/glm-5.2",+ ),+ ],+ ids=["opus_first", "fable_first_main", "override_beats_ordering"],+ )+ def test_recommended_default_nous_paid_cost_safe_policy(+ self, monkeypatch, model_ordering, expected_model,+ ):+ """Regression for PR #51493 maintainer feedback (Teknium + DavidMetcalfe).++ The interactive Nous recommended default must use the shared+ cost-safe silent policy: preferred catalog label when present,+ else first non-frontier (Opus / Fable) entry. Covers both the+ current Fable-first catalog and a future Opus-first catalog.+ """+ import hermes_cli.models as models_mod+ from hermes_cli.web_routers.models import get_recommended_default_model++ monkeypatch.setattr(+ models_mod, "get_curated_nous_model_ids", lambda: list(model_ordering),+ )+ import hermes_cli.models_pricing as mp+ monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})+ monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)+ monkeypatch.setattr(+ models_mod, "union_with_portal_paid_recommendations",+ lambda ids, pricing, url: (ids, pricing),+ )+ monkeypatch.setattr(+ models_mod, "get_preferred_silent_default_model",+ lambda provider="openrouter": "z-ai/glm-5.2",+ )++ result = get_recommended_default_model(provider="nous")+ assert result["provider"] == "nous"+ assert result["model"] == expected_model+ assert result["free_tier"] is False++ def test_recommended_default_nous_paid_falls_back_when_all_frontier(self, monkeypatch):+ """If every curated entry is a frontier tier (Opus / Fable), fall+ back to the head of the list so the picker is never empty."""+ import hermes_cli.models as models_mod+ from hermes_cli.web_routers.models import get_recommended_default_model++ monkeypatch.setattr(+ models_mod, "get_curated_nous_model_ids",+ lambda: ["anthropic/claude-fable-5", "anthropic/claude-opus-4.8"],+ )+ import hermes_cli.models_pricing as mp+ monkeypatch.setattr(mp, "get_pricing_for_provider", lambda provider: {})+ monkeypatch.setattr(models_mod, "check_nous_free_tier", lambda *, force_fresh=False: False)+ monkeypatch.setattr(+ models_mod, "union_with_portal_paid_recommendations",+ lambda ids, pricing, url: (ids, pricing),+ )+ monkeypatch.setattr(+ models_mod, "get_preferred_silent_default_model",+ lambda provider="openrouter": "z-ai/glm-5.2",+ )++ result = get_recommended_default_model(provider="nous")+ assert result["model"] == "anthropic/claude-fable-5"diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.pyindex 639fbc49198..2271407e6f6 100644--- a/tests/tools/test_approval.py+++ b/tests/tools/test_approval.py@@ -2112,73 +2112,3 @@ class TestCliApprovalTimeoutClassifiedSeparately:assert result.get("user_consent") is Falseassert "timed out without user response" in result["message"]assert "Silence is not consent" in result["message"]---# launchd verbs that stop, unload or deregister a running gateway. `disable`-# does not stop a live job on its own, but it is what makes an unload survive-# a reboot, so it belongs to the same family.-GATEWAY_LIFECYCLE_LAUNCHCTL = (- "launchctl kickstart -k gui/501/ai.hermes.gateway",- "launchctl unload ~/Library/LaunchAgents/ai.hermes.gateway.plist",- "launchctl load ~/Library/LaunchAgents/ai.hermes.gateway.plist",- "launchctl stop ai.hermes.gateway",- "launchctl restart ai.hermes.gateway",- "launchctl bootout gui/501/ai.hermes.gateway",- "launchctl remove ai.hermes.gateway",- "launchctl disable gui/501/ai.hermes.gateway",-)---class TestLifecycleGuardLaunchctlParity:- """The in-gateway hard block must cover every launchd verb the approval- layer already treats as gateway lifecycle.-- These two layers are not interchangeable. In ``tools/terminal_tool.py``- under ``_HERMES_GATEWAY == "1"``, the ``cron.lifecycle_guard`` block is- documented as applying unconditionally ("force=True cannot help here"),- while ``detect_dangerous_command`` below it is explicitly skipped when- ``force=True``. A verb covered only by the approval layer is therefore- reachable from inside the gateway, where SIGTERM propagates to the child- before the command completes and the service may never come back (#74973).-- ``bootout`` was missing exactly this way: it is the modern replacement for- the ``unload`` the guard already listed. See #80260.- """-- def test_hard_block_covers_every_lifecycle_verb(self):- from cron.lifecycle_guard import contains_gateway_lifecycle_command-- for cmd in GATEWAY_LIFECYCLE_LAUNCHCTL:- assert contains_gateway_lifecycle_command(cmd) is True, cmd-- def test_bypassable_layer_is_never_stricter(self):- """One-directional invariant: anything ``detect_dangerous_command``- flags as gateway lifecycle, the hard block must also catch.-- Not equality — the hard block is legitimately stricter (it also covers- ``load``/``restart``, which the approval layer leaves alone). What must- never happen is the reverse: a command stopped only by the layer that- ``force=True`` skips, leaving no cover inside the gateway."""- from cron.lifecycle_guard import contains_gateway_lifecycle_command-- for cmd in GATEWAY_LIFECYCLE_LAUNCHCTL:- dangerous, _, _ = detect_dangerous_command(cmd)- if not dangerous:- continue- assert contains_gateway_lifecycle_command(cmd) is True, (- f"approval layer flags this but the unbypassable hard block "- f"does not: {cmd}"- )-- def test_unrelated_labels_are_not_blocked(self):- """The label anchor must still scope this to the gateway — unrelated- services, including other Hermes ones, stay runnable."""- from cron.lifecycle_guard import contains_gateway_lifecycle_command-- for cmd in (- "launchctl bootout gui/501/com.example.unrelated",- "launchctl remove ai.hermes.update-checker",- "launchctl disable gui/501/com.apple.WindowServer",- "launchctl print system/com.apple.WindowServer",- ):- assert contains_gateway_lifecycle_command(cmd) is False, cmddiff --git a/tests/tools/test_approval_lifecycle_guard_parity.py b/tests/tools/test_approval_lifecycle_guard_parity.pynew file mode 100644index 00000000000..5e45a2d201e--- /dev/null+++ b/tests/tools/test_approval_lifecycle_guard_parity.py@@ -0,0 +1,73 @@+"""Parity between the approval layer and the in-gateway lifecycle hard block (launchctl verbs)."""++from tools.approval import detect_dangerous_command+++# launchd verbs that stop, unload or deregister a running gateway. `disable`+# does not stop a live job on its own, but it is what makes an unload survive+# a reboot, so it belongs to the same family.+GATEWAY_LIFECYCLE_LAUNCHCTL = (+ "launchctl kickstart -k gui/501/ai.hermes.gateway",+ "launchctl unload ~/Library/LaunchAgents/ai.hermes.gateway.plist",+ "launchctl load ~/Library/LaunchAgents/ai.hermes.gateway.plist",+ "launchctl stop ai.hermes.gateway",+ "launchctl restart ai.hermes.gateway",+ "launchctl bootout gui/501/ai.hermes.gateway",+ "launchctl remove ai.hermes.gateway",+ "launchctl disable gui/501/ai.hermes.gateway",+)+++class TestLifecycleGuardLaunchctlParity:+ """The in-gateway hard block must cover every launchd verb the approval+ layer already treats as gateway lifecycle.++ These two layers are not interchangeable. In ``tools/terminal_tool.py``+ under ``_HERMES_GATEWAY == "1"``, the ``cron.lifecycle_guard`` block is+ documented as applying unconditionally ("force=True cannot help here"),+ while ``detect_dangerous_command`` below it is explicitly skipped when+ ``force=True``. A verb covered only by the approval layer is therefore+ reachable from inside the gateway, where SIGTERM propagates to the child+ before the command completes and the service may never come back (#74973).++ ``bootout`` was missing exactly this way: it is the modern replacement for+ the ``unload`` the guard already listed. See #80260.+ """++ def test_hard_block_covers_every_lifecycle_verb(self):+ from cron.lifecycle_guard import contains_gateway_lifecycle_command++ for cmd in GATEWAY_LIFECYCLE_LAUNCHCTL:+ assert contains_gateway_lifecycle_command(cmd) is True, cmd++ def test_bypassable_layer_is_never_stricter(self):+ """One-directional invariant: anything ``detect_dangerous_command``+ flags as gateway lifecycle, the hard block must also catch.++ Not equality — the hard block is legitimately stricter (it also covers+ ``load``/``restart``, which the approval layer leaves alone). What must+ never happen is the reverse: a command stopped only by the layer that+ ``force=True`` skips, leaving no cover inside the gateway."""+ from cron.lifecycle_guard import contains_gateway_lifecycle_command++ for cmd in GATEWAY_LIFECYCLE_LAUNCHCTL:+ dangerous, _, _ = detect_dangerous_command(cmd)+ if not dangerous:+ continue+ assert contains_gateway_lifecycle_command(cmd) is True, (+ f"approval layer flags this but the unbypassable hard block "+ f"does not: {cmd}"+ )++ def test_unrelated_labels_are_not_blocked(self):+ """The label anchor must still scope this to the gateway — unrelated+ services, including other Hermes ones, stay runnable."""+ from cron.lifecycle_guard import contains_gateway_lifecycle_command++ for cmd in (+ "launchctl bootout gui/501/com.example.unrelated",+ "launchctl remove ai.hermes.update-checker",+ "launchctl disable gui/501/com.apple.WindowServer",+ "launchctl print system/com.apple.WindowServer",+ ):+ assert contains_gateway_lifecycle_command(cmd) is False, cmddiff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex b9ec3898421..4bd174b6086 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -23416,93 +23416,3 @@ def test_named_profile_without_backend_stays_local_under_ssh_launch(monkeypatch,monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "plain" else None)assert server._completion_cwd({"profile": "plain", "cwd": launch, "cwd_explicit": False}) == launch---def test_session_branch_idempotency_key_dedupes_retry(monkeypatch, tmp_path):- """A retried session.branch with the SAME idempotency_key returns the SAME- child instead of a duplicate (#65410): a branch whose first response was- lost must not leave two children behind. The hit answers the SAME result- shape (title, parent, message_count) without re-copying the transcript."""-- class ProfileDB:- def __init__(self, db_path=None):- pass-- def get_session_title(self, _key):- return "parent"-- def get_next_title_in_lineage(self, current):- return f"{current} (branch)"-- def create_session(self, new_key, **kwargs):- pass-- def append_messages_batch(self, session_id, messages, **kwargs):- return list(range(1, len(messages) + 1))-- def set_session_title(self, key, title):- return True-- def get_session(self, key):- return {"id": key, "cwd": str(tmp_path)}-- def update_session_cwd(self, *a, **k):- return None-- def close(self):- return None-- class FakeAgent:- def __init__(self):- self.model = "test-model"- self.session_id = None-- parent = {- "session_key": "parent-key",- "history": [{"role": "user", "content": "hi"}],- "history_lock": threading.Lock(),- "running": False,- "cols": 80,- "profile_home": None,- "source": "tui",- "agent": FakeAgent(),- "created_at": 1.0,- "last_active": 1.0,- "cwd": str(tmp_path),- }- server._sessions["parent"] = parent- monkeypatch.setattr(server, "_get_db", lambda: ProfileDB())- monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)- monkeypatch.setattr(server, "_claim_active_session_slot", lambda *a, **k: (None, None))- monkeypatch.setattr(server, "_make_agent", lambda *a, **k: FakeAgent())- monkeypatch.setattr(server, "_set_session_context", lambda *a, **k: {})- monkeypatch.setattr(server, "_clear_session_context", lambda *a, **k: None)- monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")- monkeypatch.setattr(server, "_session_cwd", lambda s: str(tmp_path))- monkeypatch.setattr(server, "_register_session_cwd", lambda *a, **k: None)- monkeypatch.setattr(server, "_attach_worker", lambda *a, **k: None)- server._idempotency_keys.clear()- try:- params = {"session_id": "parent", "name": "forked", "idempotency_key": "branch-live-retry-1"}- first = server.handle_request({"id": "b1", "method": "session.branch", "params": dict(params)})- assert "result" in first, first- first_sid = first["result"]["session_id"]- first_key = first["result"]["stored_session_id"]- assert first["result"]["title"] == "forked"- assert first["result"]["parent"] == "parent-key"-- # Client retries after a lost response: same key, same params.- second = server.handle_request({"id": "b2", "method": "session.branch", "params": dict(params)})- assert "result" in second, second- assert second["result"]["session_id"] == first_sid- assert second["result"]["stored_session_id"] == first_key- assert second["result"]["title"] == "forked"- assert second["result"]["parent"] == "parent-key"-- # Only ONE child runtime exists besides the parent.- children = [sid for sid, s in server._sessions.items() if sid != "parent"]- assert len(children) == 1- finally:- for k in list(server._sessions):- server._sessions.pop(k, None)- server._idempotency_keys.clear()diff --git a/tests/tui_gateway/test_tui_gateway_server_branch_idempotency.py b/tests/tui_gateway/test_tui_gateway_server_branch_idempotency.pynew file mode 100644index 00000000000..4d61c9e6e82--- /dev/null+++ b/tests/tui_gateway/test_tui_gateway_server_branch_idempotency.py@@ -0,0 +1,140 @@+"""TUI gateway ``session.branch`` idempotency: a retried branch returns the same child (#65410)."""++import threading+import time++import pytest++from tui_gateway import server++[email protected](autouse=True)+def _neuter_agent_prewarm_timer(request, monkeypatch):+ """Stub the deferred agent pre-warm timer (mirrors test_tui_gateway_server.py).++ ``session.create``/``session.branch`` paths may arm a background+ ``threading.Timer`` that calls whatever ``server._make_agent`` is patched in+ AT FIRE TIME; left live it lands in a later test's mock. Tests that exercise+ the deferred build itself opt back in with ``@pytest.mark.real_agent_prewarm``.+ """+ if request.node.get_closest_marker("real_agent_prewarm"):+ yield+ return+ monkeypatch.setattr(server, "_schedule_agent_build", lambda *a, **k: None)+ yield++[email protected](autouse=True)+def _reap_leaked_notification_pollers():+ """Stop and join notification pollers leaked by each test (mirrors+ test_tui_gateway_server.py): a leaked poller steals events off the+ process-global completion queue while a later test asserts on it."""+ yield+ pollers = [+ (stop, thread)+ for stop, thread in list(server._notification_pollers)+ if thread.is_alive()+ ]+ for stop, _thread in pollers:+ stop.set()+ deadline = time.time() + 3.0+ for _stop, thread in pollers:+ remaining = deadline - time.time()+ if remaining <= 0:+ break+ thread.join(timeout=remaining)+ server._notification_pollers[:] = [+ (stop, thread)+ for stop, thread in server._notification_pollers+ if thread.is_alive()+ ]+++def test_session_branch_idempotency_key_dedupes_retry(monkeypatch, tmp_path):+ """A retried session.branch with the SAME idempotency_key returns the SAME+ child instead of a duplicate (#65410): a branch whose first response was+ lost must not leave two children behind. The hit answers the SAME result+ shape (title, parent, message_count) without re-copying the transcript."""++ class ProfileDB:+ def __init__(self, db_path=None):+ pass++ def get_session_title(self, _key):+ return "parent"++ def get_next_title_in_lineage(self, current):+ return f"{current} (branch)"++ def create_session(self, new_key, **kwargs):+ pass++ def append_messages_batch(self, session_id, messages, **kwargs):+ return list(range(1, len(messages) + 1))++ def set_session_title(self, key, title):+ return True++ def get_session(self, key):+ return {"id": key, "cwd": str(tmp_path)}++ def update_session_cwd(self, *a, **k):+ return None++ def close(self):+ return None++ class FakeAgent:+ def __init__(self):+ self.model = "test-model"+ self.session_id = None++ parent = {+ "session_key": "parent-key",+ "history": [{"role": "user", "content": "hi"}],+ "history_lock": threading.Lock(),+ "running": False,+ "cols": 80,+ "profile_home": None,+ "source": "tui",+ "agent": FakeAgent(),+ "created_at": 1.0,+ "last_active": 1.0,+ "cwd": str(tmp_path),+ }+ server._sessions["parent"] = parent+ monkeypatch.setattr(server, "_get_db", lambda: ProfileDB())+ monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)+ monkeypatch.setattr(server, "_claim_active_session_slot", lambda *a, **k: (None, None))+ monkeypatch.setattr(server, "_make_agent", lambda *a, **k: FakeAgent())+ monkeypatch.setattr(server, "_set_session_context", lambda *a, **k: {})+ monkeypatch.setattr(server, "_clear_session_context", lambda *a, **k: None)+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")+ monkeypatch.setattr(server, "_session_cwd", lambda s: str(tmp_path))+ monkeypatch.setattr(server, "_register_session_cwd", lambda *a, **k: None)+ monkeypatch.setattr(server, "_attach_worker", lambda *a, **k: None)+ server._idempotency_keys.clear()+ try:+ params = {"session_id": "parent", "name": "forked", "idempotency_key": "branch-live-retry-1"}+ first = server.handle_request({"id": "b1", "method": "session.branch", "params": dict(params)})+ assert "result" in first, first+ first_sid = first["result"]["session_id"]+ first_key = first["result"]["stored_session_id"]+ assert first["result"]["title"] == "forked"+ assert first["result"]["parent"] == "parent-key"++ # Client retries after a lost response: same key, same params.+ second = server.handle_request({"id": "b2", "method": "session.branch", "params": dict(params)})+ assert "result" in second, second+ assert second["result"]["session_id"] == first_sid+ assert second["result"]["stored_session_id"] == first_key+ assert second["result"]["title"] == "forked"+ assert second["result"]["parent"] == "parent-key"++ # Only ONE child runtime exists besides the parent.+ children = [sid for sid, s in server._sessions.items() if sid != "parent"]+ assert len(children) == 1+ finally:+ for k in list(server._sessions):+ server._sessions.pop(k, None)+ server._idempotency_keys.clear()