The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: coordinate shared mutations and publish committed revisions
Tekniumeb42a0021f05
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex b620ed87ce9..7ccc64f2915 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -179,15 +179,8 @@ class AuthorityConnection:return asdict(receipt)async def mutate(self, ref, params):- from hermes_state_runtime import mutate_runtime_session- self.authority.authorize(self.actor, ref, 'session:control')- self.authority._require_admission_open()- if set(params) != {'session_id', 'request_id', 'expected_revision', 'operation', 'payload'}:- raise RuntimeStoreError('invalid_params')- return mutate_runtime_session(- self.authority.db, epoch=self.authority.epoch, principal_id=self.actor.subject,- session_id=ref.session_id, request_id=params['request_id'],- expected_revision=params['expected_revision'], operation=params['operation'], payload=params['payload'])+ from gateway.session_mutations import mutate_session+ return await mutate_session(self.authority, self.actor, ref, params)async def receipt(self, ref, params):return asdict(await self.authority.receipt(self.actor, ref, params.get('admission_id')))diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pynew file mode 100644index 00000000000..7ae0184dbf5--- /dev/null+++ b/gateway/session_mutations.py@@ -0,0 +1,60 @@+"""Action-specific authority mutations, shared by WS and authenticated HTTP.++No legacy slash handler is executed after a receipt: those handlers own separate+transactions. Reset/branch/compress/model need prepared runtime publication and+remain explicitly unavailable until that contract is implemented.+"""+from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session++_METADATA = frozenset({'rename', 'archive', 'sidebar'})+_RUNTIME_ACTIONS = frozenset({'reset', 'branch', 'compress', 'model'})+_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})+++async def mutate_session(authority, actor, ref, params):+ if (set(params) - {'expected_generation'} != _FIELDS+ or params['session_id'] != ref.session_id):+ raise RuntimeStoreError('invalid_params')+ operation = params['operation']+ if not isinstance(operation, str):+ raise RuntimeStoreError('invalid_params')+ if operation == 'import':+ if actor.profile_id != authority.profile_id or ref.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if 'session:create' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ else:+ authority.authorize(actor, ref, 'session:control')+ authority._require_admission_open()+ live = authority.sessions.get(ref.session_id)++ applied = False++ def live_guard():+ nonlocal applied+ applied = True+ if operation in _METADATA or operation == 'import':+ return+ if live is not None and live.task is not None and not live.task.done():+ raise RuntimeStoreError('session_busy')+ if operation == 'delete':+ # Route retirement must commit with deletion, not recreate the same+ # physical ID on the next native message. Do not fake that handoff.+ store = getattr(authority.runner, 'session_store', None)+ if store is not None and store.lookup_by_session_id(ref.session_id) is not None:+ raise RuntimeStoreError('runtime_coordination_required')+ if operation == 'rewind' and not callable(getattr(authority.runner, '_evict_cached_agent', None)):+ raise RuntimeStoreError('runtime_coordination_required')++ if operation in _RUNTIME_ACTIONS:+ live_guard()+ raise RuntimeStoreError('runtime_coordination_required')+ result = 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)+ if applied and live is not None:+ if operation == 'rewind':+ authority.runner._evict_cached_agent(live.route)+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')+ return resultdiff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex 7cfbb26f48e..6bb61a16b6f 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -173,7 +173,8 @@ def recover_session_inputs(db, *, epoch: int) -> int:def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,request_id: str, expected_revision: int,- operation: str, payload: dict, expected_generation: int | None = None) -> dict:+ operation: str, payload: dict, expected_generation: int | None = None,+ _live_guard=None) -> dict:"""Commit a closed metadata edit and its retry receipt in the same transaction.Caller authorizes the principal and resolves the canonical session. These@@ -215,6 +216,8 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: strraise RuntimeStoreError('revision_conflict')if expected_generation is not None and (session is None or session['runtime_generation'] != expected_generation):raise RuntimeStoreError('stale_generation')+ if _live_guard is not None:+ _live_guard()affected, projection = apply_action(db, conn, session_id, operation, payload)conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',[(target,) for target in affected])diff --git a/tests/gateway/test_session_mutation_coordinator.py b/tests/gateway/test_session_mutation_coordinator.pynew file mode 100644index 00000000000..21ae85eccb0--- /dev/null+++ b/tests/gateway/test_session_mutation_coordinator.py@@ -0,0 +1,55 @@+"""Shared mutation publication and live-state coordination."""+from types import SimpleNamespace+import asyncio+import pytest+from gateway.session_authority import LiveSession, SessionAuthority+from gateway.session_controls import AuthorityConnection+from hermes_state import SessionDB+import hermes_state_runtime as rt+++async def test_metadata_mutation_publishes_once_while_work_is_queued(tmp_path):+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('s', source='test')+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ live = authority.sessions['s'] = LiveSession(None, 'route')+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ rt.admit_session_input(db, epoch=epoch, principal_id='human', session_id='s', request_id='input', payload={'text': 'keep'})+ watermark = live.event_stream.watermark()+ request = {'id': 1, 'method': 'session.mutate', 'params': {'session_id': 's', 'request_id': 'edit',+ 'expected_revision': 0, 'operation': 'sidebar', 'payload': {'title': 'Title', 'pinned': True}}}+ try:+ first = await owner.dispatch(request)+ assert first['result']['revision'] == 1+ events = live.event_stream.since(*watermark)['events']+ assert len(events) == 1 and events[0]['type'] == 'session.updated'+ assert events[0]['payload'] == first['result']+ assert await owner.dispatch(request) == first+ assert live.event_stream.since(*watermark)['events'] == events+ assert rt.list_session_admissions(db, session_id='s')[0]['status'] == 'queued'+ finally:+ await owner.close()+++async def test_rewind_refuses_live_task_even_before_admission_claim(tmp_path):+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('s', source='test')+ db.append_message('s', role='user', content='keep')+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ live = authority.sessions['s'] = LiveSession(None, 'route')+ live.task = asyncio.create_task(asyncio.Event().wait())+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ try:+ response = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {'session_id': 's',+ 'request_id': 'rewind', 'expected_revision': 0, 'expected_generation': 0,+ 'operation': 'rewind', 'payload': {'target_message_id': db.get_messages('s')[0]['id']}}})+ assert response['error']['message'] == 'session_busy'+ assert db.get_messages('s')[0]['content'] == 'keep'+ finally:+ live.task.cancel()+ await asyncio.gather(live.task, return_exceptions=True)+ await owner.close()