The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): remove editor MCP on an empty load, fence branches before discovery
unsupportedpastels39f81e0d5817
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex bf8382ebca3..31c646a853a 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -355,11 +355,14 @@ class GatewayACPAgent(acp.Agent):await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text("Attached to the gateway's existing session policy; editor cwd is not applied.\n"))resume_params = {}- if mcp_servers:+ if mcp_servers is not None:+ # A list, empty included, is the editor's selection (load always carries one); a resume+ # that omits it keeps the session's servers. An owner without editor MCP bound none.descriptor = await client.rpc("runtime.describe")- if "acp-session-mcp-v1" not in descriptor.get("capabilities", []):+ if "acp-session-mcp-v1" in descriptor.get("capabilities", []):+ resume_params['editor'] = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]}+ elif mcp_servers:raise GatewayClientError("acp_mcp_policy_unavailable")- resume_params['editor'] = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]}try:snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)except GatewayRPCError as exc:@@ -370,8 +373,10 @@ class GatewayACPAgent(acp.Agent):await self._rebind_editor_mcp(client, session_id, resume_params['editor'])snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)self._snapshots[session_id] = snapshot- if 'editor' in resume_params:+ if resume_params.get('editor', {}).get('mcp_servers'):self._editor_mcp[session_id] = resume_params['editor']+ elif 'editor' in resume_params:+ self._editor_mcp.pop(session_id, None)from acp_adapter.server import _history_replay_updatesif self._conn:for update in _history_replay_updates(snapshot["messages"]):diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.pyindex da736d05144..8331f3c16ec 100644--- a/gateway/session_local_mcp.py+++ b/gateway/session_local_mcp.py@@ -266,18 +266,24 @@ def attach_editor_mcp(authority, policy, servers):def resume_editor_mcp(authority, ref, editor):- """Call after ordinary resume authorization, before attaching the viewer."""+ """Call after ordinary resume authorization, before attaching the viewer. An explicit empty list+ is a selection too: on a session holding editor servers it conflicts, so the editor removes them+ through the fenced ``editor_mcp`` change; an omitted list keeps them."""if editor is None:returnfrom gateway.session_local_editor import validate_editorfrom gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ servers = editor.get('mcp_servers') if isinstance(editor, dict) else None+ if servers == [] and (policy is None or not policy.editor_mcp_json):+ return # nothing to remove, whichever surface created the sessionif policy is None:raise RuntimeStoreError('acp_mcp_policy_conflict')validate_editor(policy.source, editor)- servers = editor.get('mcp_servers', [])if servers:attach_editor_mcp(authority, policy, servers)+ elif servers is not None:+ raise RuntimeStoreError('acp_mcp_policy_conflict')def retire_editor_mcp(authority, sid):@@ -387,29 +393,24 @@ async def refreeze_editor_mcp(authority, ref, live):if not complete or (schemas == data['schemas'] and not drifted):returntry:- await _commit_refreeze(authority, ref, live, servers)+ await _commit_refreeze(authority, ref, servers)except RuntimeStoreError:# The FIFO must not pause on it: the turn then reports the drift as before.logger.warning('Editor MCP schemas of session %s changed; re-freeze failed', ref.session_id, exc_info=True)-async def _commit_refreeze(authority, ref, live, servers):- from gateway.session_local import publish_local_policy+async def _commit_refreeze(authority, ref, servers):+ """The ``editor_mcp`` change on the owning principal's behalf, through ``session.mutate``'s own+ writer (the drain holds the session's locks, and a schema re-check needs no capability)."""+ from gateway.session_mutations import write_mutationfrom hermes_state_local import local_receipt- from hermes_state_runtime import mutate_runtime_sessionowner = await asyncio.to_thread(local_receipt, authority.db, ref.session_id)row = await asyncio.to_thread(authority.db.get_session, ref.session_id)payload, servers = private_mutation_payload('editor_mcp', {'mcp_servers': servers})- fields = dict(epoch=authority.epoch, principal_id=owner['principal_id'], session_id=ref.session_id,- request_id='editor-mcp-refreeze:' + uuid.uuid4().hex, expected_revision=row['runtime_revision'],- expected_generation=row['runtime_generation'], operation='editor_mcp', payload=payload)- prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepare_only=True)- prepared = await prepare_editor_mcp(authority, live, payload, prepared, servers=servers)- result = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepared=prepared)- install_editor_mcp(authority, ref.session_id, servers)- publish_local_policy(authority, ref.session_id)- live.event_stream.publish(ref.session_id, result, event_type='session.updated')- announce_tools_changed(live, ref.session_id, result)+ params = {'session_id': ref.session_id, 'request_id': 'editor-mcp-refreeze:' + uuid.uuid4().hex,+ 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],+ 'operation': 'editor_mcp', 'payload': payload}+ await write_mutation(authority, ref, params, servers, principal_id=owner['principal_id'])def _child_secret_ref(authority, child, parent, policy):@@ -422,10 +423,13 @@ def _child_secret_ref(authority, child, parent, policy):return replace(policy, config_secret_ref=config_reference(authority, child, policy, secrets))-async def prepare_branch_editor(authority, ref, servers):+async def prepare_branch_editor(authority, ref, servers, gate):"""``(prepared, servers)`` for a fork of an editor session: the child's selection under its OWNscope, from the fork's list or else a copy of the parent's borrowed servers. The child never- shares the parent's scope or connections. ``(None, None)`` when no editor servers are involved."""+ shares the parent's scope or connections. ``(None, None)`` when no editor servers are involved.++ Discovery starts every server, so *gate* (the branch's prepare-only fences: receipt, revision,+ generation, idle) runs first; an exact retry's durable receipt comes back as ``prepared``."""from gateway.session_policy import restore_policyfrom hermes_state_keys import local_identityfrom hermes_state_local import local_receipt@@ -443,11 +447,14 @@ async def prepare_branch_editor(authority, ref, servers):servers = json.loads(_json(servers))elif parent.source != 'acp':raise RuntimeStoreError('invalid_params')+ gated = await gate()+ if 'snapshot' not in gated:+ return gated, serversrequest_id = 'branch:' + uuid.uuid4().hexchild = local_identity(saved['profile_id'], saved['principal_id'], request_id)policy, _ = await asyncio.to_thread(rebind_editor_mcp, authority, child, parent, servers)policy = _child_secret_ref(authority, child, parent, policy)- return {'request_id': request_id, 'child': child, 'parent_editor_mcp_json': parent.editor_mcp_json,+ return {**gated, 'request_id': request_id, 'child': child, 'parent_editor_mcp_json': parent.editor_mcp_json,'editor_mcp_json': policy.editor_mcp_json, 'toolsets': list(policy.toolsets),'config_secret_ref': policy.config_secret_ref}, serversdiff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 9ff7bd6619e..0ee94c851fb 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -118,8 +118,27 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):if operation == 'branch' and 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')authority._require_admission_open()- live = authority.sessions.get(ref.session_id)+ def authorize_write(conn):+ from hermes_state_mutation_binding import authorize_history, import_history_control+ if operation == 'import':+ import_history_control(conn, actor, imported_ids)+ return+ if not authorize_history(conn, actor, ref.session_id, claim=True):+ raise RuntimeStoreError('permission_denied')++ return await write_mutation(authority, ref, params, editor_servers, principal_id=actor.subject,+ authorize_write=authorize_write if cold_history or operation == 'import' else None,+ commit_lock=commit_lock)+++async def write_mutation(authority, ref, params, editor_servers, *, principal_id, authorize_write=None,+ commit_lock=None):+ """The writer phase of ``session.mutate``, and of the admission-start editor MCP re-freeze+ (``refreeze_editor_mcp``): fenced prepare, the receipt commit, then its runtime projections.+ The caller authorized the change and holds the session's locks; this takes neither."""+ operation = params['operation']+ live = authority.sessions.get(ref.session_id)applied = Falsedef live_guard(targets):@@ -138,24 +157,22 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):if operation in {'rewind', 'reset'} and not callable(getattr(authority.runner, '_evict_cached_agent', None)):raise RuntimeStoreError('runtime_coordination_required')- def authorize_write(conn):- from hermes_state_mutation_binding import authorize_history, import_history_control- if operation == 'import':- import_history_control(conn, actor, imported_ids)- return- if not authorize_history(conn, actor, ref.session_id, claim=True):- raise RuntimeStoreError('permission_denied')+ fields = dict(epoch=authority.epoch, principal_id=principal_id, session_id=ref.session_id,+ request_id=params['request_id'], expected_revision=params['expected_revision'],+ expected_generation=params.get('expected_generation'), operation=operation,+ payload=params['payload'], _live_guard=live_guard)- prepared = branch_editor = None+ async def prepare_only():+ # Its own BEGIN IMMEDIATE, so off the loop like the commit below.+ return await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepare_only=True)++ prepared = Noneif operation == 'branch':from gateway.session_local_mcp import prepare_branch_editor- branch_editor, editor_servers = await prepare_branch_editor(authority, ref, editor_servers)+ # Discovery launches the child's servers: the fences (receipt, revision, generation, idle) answer first.+ prepared, editor_servers = await prepare_branch_editor(authority, ref, editor_servers, prepare_only)if operation in {*_POLICY, 'compress'}:- # Its own BEGIN IMMEDIATE, so off the loop like the commit below.- prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,- principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],- expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),- operation=operation, payload=params['payload'], _live_guard=live_guard, _prepare_only=True)+ prepared = await prepare_only()if 'snapshot' in prepared:from gateway.session_mutation_model import prepare_modelfrom gateway.session_mutation_compress import prepare_compress@@ -164,12 +181,12 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE,'editor_mcp': partial(prepare_editor_mcp, servers=editor_servers)}[operation]prepared = await prepare(authority, live, params['payload'], prepared)- applied = Falseif prepared.get('status') in {'preview', 'noop', 'confirmation_required'}:# ``--preview`` and a compress that removes nothing are read-only reports, and a# guarded model target awaits the user's confirmation: no receipt, no publication,# no eviction.return {'session_id': ref.session_id, 'operation': operation, **prepared}+ applied = Falseasync with commit_lock or nullcontext():if prepared is not None and 'snapshot' not in prepared:# Exact retry: the durable receipt is the result. Never re-prepare (compress@@ -179,39 +196,9 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):else:# The receipt transaction is synchronous SQLite: run it off the event loop so a large# state.db or a contended writer lock never stalls other clients (main 1769024ca3b).- result = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,- principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],- expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),- operation=operation, payload=params['payload'], _live_guard=live_guard, _prepared=branch_editor or prepared,- _authorize_write=authorize_write if cold_history or operation == 'import' else None)- # Post-commit projections are idempotent reads of the committed receipt, so exact- # retries repeat them (like delete's retirement); only the one-shot event is fenced.- current = authority.db.get_session(ref.session_id)- owns_projection = current is not None and (- current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))- if operation == 'compress' and applied and owns_projection and live is not None:- # Before the boundary evicts the agent whose compressor holds the running count.- from gateway.session_usage import note_compression- note_compression(authority, ref, live)- elif operation == 'reset' and applied and live is not None:- live.compression_count = 0 # a fresh conversation, as main's /new builds a fresh agent- if editor_servers is not None and (operation == 'branch' or owns_projection):- # Before the policy publication below, so no execution sees the policy without them.- from gateway.session_local_mcp import install_editor_mcp- install_editor_mcp(authority, result.get('branched_session_id', ref.session_id), editor_servers)- if operation == 'editor_mcp' and not editor_servers:- # An empty selection: the old servers must not keep running for a viewer.- from gateway.session_local_mcp import retire_editor_mcp- await asyncio.to_thread(retire_editor_mcp, authority, ref.session_id)- if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:- _project_committed(authority, ref, operation, result)- if live is not None:- if operation == 'rewind' and owns_projection:- authority.runner._evict_cached_agent(live.route)- if applied:- live.event_stream.publish(ref.session_id, result, event_type='session.updated')- from gateway.session_local_mcp import announce_tools_changed- announce_tools_changed(live, ref.session_id, result)+ result = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields,+ _prepared=prepared, _authorize_write=authorize_write)+ await _project_result(authority, ref, live, params, result, editor_servers, applied=applied)if operation == 'delete':# After the synchronous projections (no yield before retirement), off the loop: the# retired-media owner check is a messages-table pass (exact retries repeat it too).@@ -220,6 +207,39 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):return result+async def _project_result(authority, ref, live, params, result, editor_servers, *, applied):+ """A committed receipt's projections, under the writer's commit lock. They are idempotent reads+ of the committed receipt, so exact retries repeat them (like delete's retirement); only the+ one-shot event is fenced."""+ operation = params['operation']+ current = authority.db.get_session(ref.session_id)+ owns_projection = current is not None and (+ current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))+ if operation == 'compress' and applied and owns_projection and live is not None:+ # Before the boundary evicts the agent whose compressor holds the running count.+ from gateway.session_usage import note_compression+ note_compression(authority, ref, live)+ elif operation == 'reset' and applied and live is not None:+ live.compression_count = 0 # a fresh conversation, as main's /new builds a fresh agent+ if editor_servers is not None and (operation == 'branch' or owns_projection):+ # Before the policy publication below, so no execution sees the policy without them.+ from gateway.session_local_mcp import install_editor_mcp+ install_editor_mcp(authority, result.get('branched_session_id', ref.session_id), editor_servers)+ if operation == 'editor_mcp' and not editor_servers:+ # An empty selection: the old servers must not keep running for a viewer.+ from gateway.session_local_mcp import retire_editor_mcp+ await asyncio.to_thread(retire_editor_mcp, authority, ref.session_id)+ if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:+ _project_committed(authority, ref, operation, result)+ if live is not None:+ if operation == 'rewind' and owns_projection:+ authority.runner._evict_cached_agent(live.route)+ if applied:+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')+ from gateway.session_local_mcp import announce_tools_changed+ announce_tools_changed(live, ref.session_id, result)++def _project_committed(authority, ref, operation, result):"""Publish a committed receipt's runtime projections (safe to repeat on exact retry)."""if operation in _POLICY:diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex eb7f2f34613..daa942e2fea 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -299,7 +299,12 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str_authorize_write(conn)if _prepare_only:from hermes_state_mutation_prepared import local_snapshot- return {'snapshot': local_snapshot(db, conn, session_id)}+ snapshot = local_snapshot(db, conn, session_id)+ if operation == 'branch':+ # The branch commit's own idle rule (queued input too), before the owner starts servers.+ from hermes_state_mutation_guards import require_idle+ require_idle(db, conn, list({session_id, snapshot['target']}))+ return {'snapshot': snapshot}affected, projection = apply_action(db, conn, session_id, operation, payload, prepared=_prepared)conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',[(target,) for target in affected])diff --git a/tests/acp_adapter/test_gateway_editor_mcp_held.py b/tests/acp_adapter/test_gateway_editor_mcp_held.pyindex 9f827ff9c83..111cb29a9d6 100644--- a/tests/acp_adapter/test_gateway_editor_mcp_held.py+++ b/tests/acp_adapter/test_gateway_editor_mcp_held.py@@ -9,8 +9,9 @@ import sysimport pytest-from tests.acp_adapter.test_gateway_editor_mcp import MCPModelPeer, _completed, _peers_running, _policies-from tests.acp_adapter.test_gateway_sessions import viewer+from tests.acp_adapter.test_gateway_editor_mcp import (+ MCPModelPeer, _completed, _peers_running, _policies, initialize, prompt)+from tests.acp_adapter.test_gateway_sessions import editor, viewerfrom tests.waiting import async_wait_until# The tool description is read on every tools/list, so one live process can change its tools.@@ -81,3 +82,28 @@ async def test_empty_selection_closes_the_held_connections(daemon, spec, tmp_patawait async_wait_until(lambda: not _peers_running(daemon[1]['pid']), timeout=20,what='held editor server closed by the empty selection')assert _policies(daemon[0], sid) == [None]++[email protected]("linux")+async def test_acp_load_with_no_servers_removes_them_and_resume_without_a_list_keeps_them(daemon, spec, tmp_path):+ """``session/load`` always carries ``mcpServers`` (the schema requires it), so ``[]`` there is the+ editor's selection: the owner's ``editor_mcp`` removal. ``session/resume`` may omit the list,+ which keeps the session's servers."""+ async with editor(daemon, tmp_path) as acp:+ await initialize(acp)+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[spec])+ assert 'result' in created, created+ sid = created['result']['sessionId']+ assert 'result' in await prompt(acp, sid)+ assert _peers_running(daemon[1]['pid']), 'a viewed session holds its editor server between turns'+ resumed = await acp.rpc('session/resume', sessionId=sid, cwd=str(tmp_path))+ assert 'result' in resumed, resumed+ assert _peers_running(daemon[1]['pid']), 'an omitted list keeps the servers'+ assert _policies(daemon[0], sid) != [None]+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in loaded, loaded+ # The editor is still attached: only the committed empty selection may close the process.+ await async_wait_until(lambda: not _peers_running(daemon[1]['pid']), timeout=20,+ what='held editor server closed by the empty load')+ assert _policies(daemon[0], sid) == [None]diff --git a/tests/acp_adapter/test_session_mcp_branch_gate.py b/tests/acp_adapter/test_session_mcp_branch_gate.pynew file mode 100644index 00000000000..f6433db4005--- /dev/null+++ b/tests/acp_adapter/test_session_mcp_branch_gate.py@@ -0,0 +1,102 @@+"""A fork's editor MCP discovery runs only after the branch's own fences pass (#134889 ACP-12).++Discovery launches every requested server, so a stale, busy or exact-retry ``branch`` must be+answered by the receipt, revision, generation and idle checks before any server starts.+Real authority and SQLite, real ``session.mutate`` dispatch; the discovery entry point is a spy.+"""+import asyncio+from types import SimpleNamespace++import pytest+++class _Bridge:+ def __init__(self, connection):+ self.connection = connection++ async def rpc(self, method, **params):+ reply = await self.connection.dispatch({'id': 1, 'method': method, 'params': params})+ if 'error' in reply:+ return reply['error']['message']+ return reply['result']+++def owner(tmp_path, monkeypatch, server_spec):+ from gateway import run, session_local_mcp+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'acp': []}})+ discovered = []+ real = session_local_mcp.rebind_editor_mcp++ def spy(authority, sid, policy, servers):+ discovered.append(sid)+ return real(authority, sid, policy, servers)+ monkeypatch.setattr(session_local_mcp, 'rebind_editor_mcp', spy)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)++ built = []++ async def build():+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='owner')+ built.append(authority)+ connection = AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': 'fixture'})+ ref = create_local_session(authority, connection.actor, {+ 'request_id': 'editor', 'source': 'acp', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ return authority, _Bridge(connection), ref.session_id+ try:+ yield build, discovered, {'mcp_servers': [server_spec]}+ finally:+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers+ for authority in built:+ for scope in list(getattr(authority, '_editor_mcp_held', {})):+ shutdown_mcp_servers(scope=scope)+ store.close_all_db_handles()+++def _branch(sid, payload, **fence):+ return dict(session_id=sid, request_id='fork', operation='branch', payload=payload,+ expected_revision=fence.get('revision', 0), expected_generation=fence.get('generation', 0))+++async def test_stale_branch_starts_no_editor_server(owner):+ build, discovered, payload = owner+ _, client, sid = await build()+ assert await client.rpc('session.mutate', **_branch(sid, payload, revision=7)) == 'revision_conflict'+ assert await client.rpc('session.mutate', **_branch(sid, payload, generation=7)) == 'stale_generation'+ assert discovered == []+++async def test_busy_branch_starts_no_editor_server(owner):+ from hermes_state_runtime import admit_session_input+ build, discovered, payload = owner+ authority, client, sid = await build()+ # A queued input: the branch commit's own idle rule refuses it (require_idle).+ await asyncio.to_thread(admit_session_input, authority.db, epoch=authority.epoch, principal_id='human',+ session_id=sid, request_id='queued', payload={'text': 'waiting'})+ row = authority.db.get_session(sid)+ fence = dict(revision=row['runtime_revision'], generation=row['runtime_generation'])+ assert await client.rpc('session.mutate', **_branch(sid, payload, **fence)) == 'session_busy'+ assert discovered == []+++async def test_exact_branch_retry_returns_the_receipt_without_discovery(owner):+ build, discovered, payload = owner+ _, client, sid = await build()+ first = await client.rpc('session.mutate', **_branch(sid, payload))+ assert isinstance(first, dict) and first['branched_session_id'], first+ assert discovered == [first['branched_session_id']]+ assert await client.rpc('session.mutate', **_branch(sid, payload)) == first+ assert discovered == [first['branched_session_id']], 'an exact retry must not rediscover'