The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): integrate the review lanes — union-test fallout
teknium1c0ad20dc7296
diff --git a/gateway/session_ingress_context.py b/gateway/session_ingress_context.pyindex 4898e5350f3..fb672a2fd4f 100644--- a/gateway/session_ingress_context.py+++ b/gateway/session_ingress_context.py@@ -106,9 +106,11 @@ def _binding(runner, source, profile):owner_name = profile or primaryif homes.get(owner_name) != home:raise RuntimeStoreError('profile_mismatch')+ # Same matcher as ingress stamping: a route applies only to its ``bot_profile``'s bot+ # (#104933), so the receiving adapter's owner is part of the match.matches = [route for route in runner.config.profile_routes if route.matches(source.platform.value, guild_id=source.scope_id, chat_id=source.chat_id,- thread_id=source.thread_id, parent_chat_id=source.parent_chat_id)]+ thread_id=source.thread_id, parent_chat_id=source.parent_chat_id, adapter_profile=profile)]if matches:rank = max(route.specificity for route in matches)best = [route for route in matches if route.specificity == rank]diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 773fdb0bed0..b4f83becef8 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -2053,50 +2053,6 @@ def _worker_terminal_timeout_env(return str(desired)-def _resolve_worker_cli_toolsets(hermes_home: Optional[str]) -> Optional[list[str]]:- """Return the assigned profile's effective CLI toolsets for a worker.-- Resolved at dispatch time and passed as an explicit ``--toolsets`` pin so- worker startup cannot fall back to a stale root/active-profile config or a- profile whose top-level ``toolsets`` is only the kanban orchestrator- surface. ``model_tools`` still appends the task-scoped kanban lifecycle- tools when ``HERMES_KANBAN_TASK`` is set.- """- if not hermes_home:- return None- try:- from agent.secret_scope import (- build_profile_secret_scope, is_multiplex_active, reset_secret_scope, set_secret_scope)- from hermes_constants import reset_hermes_home_override, set_hermes_home_override- from hermes_cli.config import load_config- from hermes_cli.tools_config import _get_platform_tools-- token = set_hermes_home_override(hermes_home)- # Toolset availability probes read credentials (``get_secret``); under multiplex an- # unscoped read raises and the pin was silently dropped for every worker.- secret_token = (- set_secret_scope(build_profile_secret_scope(Path(hermes_home)))- if is_multiplex_active() else None)- try:- cfg = load_config()- toolsets = sorted(_get_platform_tools(cfg, "cli"))- finally:- if secret_token is not None:- reset_secret_scope(secret_token)- reset_hermes_home_override(token)- return toolsets or None- except Exception as exc:- _kb._log.debug(- "kanban worker: could not resolve CLI toolsets for HERMES_HOME=%r (%s)",- hermes_home,- exc,- )- return None---_retagged_workspace_roots: set[str] = set()--def _retag_legacy_worker_sessions(workspaces_root_path: str) -> None:"""Reclaim pre-tag worker rows in state.db so they leave the session lists.diff --git a/tests/acp/test_gateway_controls.py b/tests/acp/test_gateway_controls.pyindex b3353e5fdff..d273bb78fc7 100644--- a/tests/acp/test_gateway_controls.py+++ b/tests/acp/test_gateway_controls.py@@ -18,14 +18,22 @@ async def test_cancel_uses_observed_generation_and_mutations_fail_explicitly(tmpagent._gateway = RPC()agent._snapshots["shared"] = {"execution_generation": 4, "revision": 7}+ # No ACP prompt in flight: another surface's running turn is not ours to interrupt.+ await agent.cancel("shared")+ assert calls == []+ # Our own queued admission is cancelled by identity; a stale answer propagates verbatim+ # (the receipt lookup is the next call, which this authority also refuses).+ agent._admissions["shared"] = "adm-1"with pytest.raises(GatewayClientError, match="stale_generation"):await agent.cancel("shared")- assert calls == [("session.interrupt", {"session_id": "shared", "execution_generation": 4})]+ assert calls[0] == ("prompt.cancel", {"session_id": "shared", "admission_id": "adm-1"})+ assert calls[1][0] == "prompt.receipt"+ calls.clear()# Model changes are prepared canonical mutations: a stale authority answer propagates# verbatim instead of being retried through any alternate writer.with pytest.raises(GatewayClientError, match="stale_generation"):await agent.set_session_model(session_id="shared", model_id="new-model")- methods = [method for method, _ in calls[1:]]+ methods = [method for method, _ in calls]assert methods and set(methods) <= {"session.resume", "session.mutate"}, methods# Edit-policy mode is still unsupported and must not reach the authority at all.before = len(calls)diff --git a/tests/acp/test_gateway_tool_projection.py b/tests/acp/test_gateway_tool_projection.pyindex e85dfbcb6fc..03b2cbde0ca 100644--- a/tests/acp/test_gateway_tool_projection.py+++ b/tests/acp/test_gateway_tool_projection.py@@ -64,6 +64,7 @@ def test_gateway_publishes_tool_arguments_and_result_for_live_viewers():runner = TurnRunner.__new__(TurnRunner)runner._ctx = Ctx()runner._approval_owner = (Authority(), 's', 3)+ runner._publish_api_tool = lambda *a, **k: None # API observer fan-out is exercised in tests/gatewayrunner.combined_tool_start_callback('call_1', 'read_file', ARGS)runner.combined_tool_complete_callback('call_1', 'read_file', ARGS, RESULT)start, complete = publisheddiff --git a/tests/acp/test_session_mcp_frozen.py b/tests/acp/test_session_mcp_frozen.pyindex 828dc60754a..465d58aeebd 100644--- a/tests/acp/test_session_mcp_frozen.py+++ b/tests/acp/test_session_mcp_frozen.py@@ -19,7 +19,7 @@ def test_editor_manifest_stays_frozen_across_live_refresh(server_spec, tmp_path)with policy_scope(p, authority=authority):names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]schemas = {n: registry.get_schema(n) for n in names}- server = next(s for n, s in _servers.items() if n.startswith('editor_'))+ server = next(s for key, s in _servers.items() if key[-1].startswith('editor_'))# The real refresh re-reads the stdio peer. A changed in-memory discovery# response is not allowed to republish schemas even when explicitly refreshed.server._tools[0].description = 'changed after first discovery'@@ -53,4 +53,4 @@ def test_silent_editor_discovery_is_bounded_and_reaps_only_itself(server_spec, tassert len(names) == 1assert 'PRIVATE_A' in registry.dispatch(names[0], {})from tools.mcp_tool import _servers- assert not any(n.startswith('editor_') for n in _servers)+ assert not any(key[-1].startswith('editor_') for key in _servers)diff --git a/tests/gateway/fixtures/authority_stream_peer.py b/tests/gateway/fixtures/authority_stream_peer.pyindex 20732d26843..77ef69f54ee 100644--- a/tests/gateway/fixtures/authority_stream_peer.py+++ b/tests/gateway/fixtures/authority_stream_peer.py@@ -225,7 +225,10 @@ async def probe(peer, target):assert [e['type'] for e in tools] == ['tool.start', 'tool.complete']assert all(e['payload']['tool_call_id'] == 'owned-tool' for e in tools)assert 'PRIVATE_REASONING_NOT_PUBLIC' not in json.dumps(events)- assert str(target) not in json.dumps(tools), 'tool args leaked into public stream'+ # Tool arguments/results are transcript data every session:read viewer can resume, so the+ # live frames carry them (ACP/Desktop parity); reasoning stays out of the stream above.+ assert tools[0]['payload']['args'].get('command') and str(target) in tools[0]['payload']['args']['command']+ assert isinstance(tools[1]['payload']['result'], str)assert adapter.sent, 'native delivery lane was lost'last = events[-1]['seq']# Same generation is still recorded after settlement; late callbacks must be inert.diff --git a/tests/gateway/fixtures/native_ingress_trust_multiplex.py b/tests/gateway/fixtures/native_ingress_trust_multiplex.pyindex f50bac0199d..ac0dea6a9ad 100644--- a/tests/gateway/fixtures/native_ingress_trust_multiplex.py+++ b/tests/gateway/fixtures/native_ingress_trust_multiplex.py@@ -30,7 +30,8 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):(transport / 'config.yaml').write_text((state / 'config.yaml').read_text())runner.config.multiplex_profiles = Truerunner.config._runtime_profile_homes = [('default', state), ('transport', transport)]- route = ProfileRoute(name='to-runtime', platform='telegram', profile='default', chat_id='mux-chat')+ route = ProfileRoute(name='to-runtime', platform='telegram', profile='default', chat_id='mux-chat',+ bot_profile='transport')runner.config.profile_routes = [route]set_multiplex_active(True)adapter = type(primary)()@@ -111,7 +112,7 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):if mode == 'multiplex':sessions_before = set(authority.sessions)runner.config.profile_routes.append(ProfileRoute(name='unowned-runtime', platform='telegram',- profile='transport', chat_id='unowned-runtime'))+ profile='transport', chat_id='unowned-runtime', bot_profile='transport'))unowned = adapter.build_source(chat_id='unowned-runtime', chat_type='dm', user_id='fixture-user')await adapter.handle_message(MessageEvent(text='NO_SECONDARY_DB_OWNER', source=unowned, message_id='unowned'))async with asyncio.timeout(10):diff --git a/tests/gateway/fixtures/native_role_peer.py b/tests/gateway/fixtures/native_role_peer.pyindex 3170ae506a1..8c6d6eb6c8b 100644--- a/tests/gateway/fixtures/native_role_peer.py+++ b/tests/gateway/fixtures/native_role_peer.py@@ -87,7 +87,7 @@ async def probe(peer):runner.config.multiplex_profiles = Truerunner.config._runtime_profile_homes = [('default', state), ('transport', transport)]runner.config.profile_routes = [ProfileRoute(name='role-route', platform='discord',- profile='default', chat_id='300')]+ profile='default', chat_id='300', bot_profile='transport')]set_multiplex_active(True)runner.adapters.clear()runner._profile_adapters = {'transport': {Platform.DISCORD: adapter}}diff --git a/tests/gateway/test_kanban_multiplex_served_profile_parity.py b/tests/gateway/test_kanban_multiplex_served_profile_parity.pyindex 928e84ceb01..b4340bb854b 100644--- a/tests/gateway/test_kanban_multiplex_served_profile_parity.py+++ b/tests/gateway/test_kanban_multiplex_served_profile_parity.py@@ -44,8 +44,8 @@ def served(tmp_path, monkeypatch):def test_worker_for_served_profile_gets_its_own_env_and_toolset_pin(served, monkeypatch):- """The dispatcher (root context) spawns alpha's worker: no launch-profile settings leak into the- child and the ``--toolsets`` pin (whose probes read credentials) is resolved under alpha's scope."""+ """The dispatcher (root context) spawns alpha's worker client: no launch-profile settings leak+ into the child; the toolset pin is resolved by alpha's owner (``kanban.run``), not the dispatcher."""kb.init_db()conn = kbc.connect()try:@@ -68,7 +68,7 @@ def test_worker_for_served_profile_gets_its_own_env_and_toolset_pin(served, monkenv = spawned["env"]assert env["HERMES_HOME"] == str(served.alpha)assert "HERMES_MODEL" not in env and "TERMINAL_ENV" not in env- assert "--toolsets" in spawned["argv"]+ assert spawned["argv"][-2:] == ["-m", "hermes_cli.kanban_worker_client"]class RecordingAdapter:diff --git a/tests/gateway/test_managed_worker_launch.py b/tests/gateway/test_managed_worker_launch.pyindex f6d58027d00..45af6edd19b 100644--- a/tests/gateway/test_managed_worker_launch.py+++ b/tests/gateway/test_managed_worker_launch.py@@ -177,7 +177,7 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathanswered = await rpc(ws, 'clarify.respond', session_id=sid,execution_generation=clarify['execution_generation'], prompt_id=clarify['prompt_id'], answer='Beta')assert answered['result']['status'] == 'resolved', answered- assert await asyncio.to_thread(peer.blocked.wait, 30), (home / 'restart.log').read_text()+ assert await asyncio.to_thread(peer.blocked.wait, 90), (home / 'restart.log').read_text()workers = query('SELECT execution_id,status FROM worker_executions WHERE session_id=?', (sid,))assert len(workers) == 1, workerschildren = [p for p in psutil.Process(owner.pid).children() if p.cmdline()[-2:] == ['-m', 'agent.managed_worker']]diff --git a/tests/gateway/test_prompt_attachments.py b/tests/gateway/test_prompt_attachments.pyindex 62d6daa15c2..1a032c59dae 100644--- a/tests/gateway/test_prompt_attachments.py+++ b/tests/gateway/test_prompt_attachments.py@@ -1,6 +1,7 @@"""Public ``prompt.submit`` attachments: scoped to the profile staging dir, committed as bytes."""from types import SimpleNamespace+import osimport pytest_ONE_PX_PNG = bytes.fromhex(@@ -65,5 +66,6 @@ async def test_staged_attachment_reaches_message_event_media(tmp_path, monkeypatassert event.media_types == ['image/png'](path,) = event.media_urlsassert path != staged, 'execution must read committed bytes, not the mutable staging file'- with open(path, 'rb') as fh:- assert fh.read() == _ONE_PX_PNG+ assert 'native-inputs' in path+ # Retained bytes are exact-retry evidence by digest only; settlement releases them.+ assert not os.path.exists(path)diff --git a/tests/gateway/test_session_operator_scope.py b/tests/gateway/test_session_operator_scope.pyindex 75e1eea44d5..f0b7c235321 100644--- a/tests/gateway/test_session_operator_scope.py+++ b/tests/gateway/test_session_operator_scope.py@@ -87,7 +87,7 @@ async def test_identity_fields_cannot_grant_operator_or_first_claim(tmp_path, momonkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})store = SessionStore(tmp_path / 'sessions', GatewayConfig())runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,- _cached_agent_for=lambda route: None)+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None)authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='fixture')owner = Principal('owner', str(tmp_path), frozenset({'session:create'}), 'owner')ref = create_local_session(authority, owner, {'request_id': 'owner', 'source': 'gui',diff --git a/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py b/tests/hermes_cli/test_kanban_worker_spawn_toolsets.pyindex f2ed93a6d0a..8042c8e9734 100644--- a/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py+++ b/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py@@ -113,33 +113,3 @@ def test_default_spawn_does_not_pass_mutable_launch_overrides(monkeypatch, tmp_p# Mutable model strings are not launch authority; the owner reads the claimed card.assert captured["cmd"][-2:] == ["-m", "hermes_cli.kanban_worker_client"]assert task.model_override not in captured["cmd"]---def test_resolve_worker_cli_toolsets_uses_profile_home_not_parent_config(monkeypatch, tmp_path):- root = tmp_path / ".hermes"- profile = root / "profiles" / "elias"- profile.mkdir(parents=True)- root.joinpath("config.yaml").write_text("platform_toolsets:\n cli:\n - kanban\n", encoding="utf-8")- profile.joinpath("config.yaml").write_text(- """-platform_toolsets:- cli:- - terminal- - web-toolsets:- - hermes-cli-""".lstrip(),- encoding="utf-8",- )- monkeypatch.setenv("HERMES_HOME", str(root))-- from hermes_cli import kanban_db as kb- from hermes_cli import kanban_db_dispatch as kbd-- resolved = kbd._resolve_worker_cli_toolsets(str(profile))-- assert resolved is not None- assert "terminal" in resolved- assert "web" in resolved- assert "kanban" in resolved # recovered worker lifecycle surface- assert resolved != ["kanban"]