The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): admit automation wakes on route identity, not display fields
unsupportedpastels91171b7f0b58
diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex e29c0080332..f262105512e 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -258,6 +258,16 @@ def _route_owner(authority, entry):else authority.logical_owner(entry.session_id))+def _delegating_session(db, session_id):+ """The conversation a (nested) delegate_task child runs under, else ``session_id``. Only the+ owner mints ``subagent`` rows, with the parent's lineage (gateway/session_worker_child.py)."""+ lineage = [session_id]+ while ((row := db.get_session(lineage[-1])) and row.get('source') == 'subagent'+ and row.get('parent_session_id') not in (None, *lineage)):+ lineage.append(row['parent_session_id'])+ return lineage[-1]++def _owner(runner, event, authority):route = event.metadata.get('gateway_session_key') or runner.session_store._generate_session_key(event.source)entry = runner.session_store.lookup_by_session_key(route)@@ -269,8 +279,10 @@ def _owner(runner, event, authority):if not expected:raise RuntimeStoreError('admission_conflict')if expected != entry.session_id:- # A completed child may follow compression, but never /new or an unrelated resume.- if authority.db.get_compression_tip(expected) != entry.session_id:+ # A completed child may follow compression, and a process a subagent started its parent+ # conversation, but never /new or an unrelated resume.+ expected = _delegating_session(authority.db, expected)+ if expected != entry.session_id and authority.db.get_compression_tip(expected) != entry.session_id:raise RuntimeStoreError('admission_conflict')return entry@@ -326,10 +338,6 @@ def admission_display(payload):return card-def _route_identity(source):- return {key: value for key, value in source.to_dict().items() if key != 'message_id'}--def committed_route_envelope(authority, entry):"""The route's last committed native envelope with connector provenance (what a producer turnborrows), or ``None`` while no human message was admitted there."""@@ -364,15 +372,20 @@ def snapshot_automation(authority, adapter, event, identity):# Recheck only the source/provenance: a completed input's retained media is already released.restored = restore_native({'text': event.text, 'native_text_v1': {key: value for key, value in envelope.items() if key != 'media'}}, runner)- # Synthetic wakes clear ``message_id`` (#52694, #123097) while the committed human source keeps- # it, so compare the routing/provenance identity, never the platform reply anchor.- if (_route_identity(restored.source) != _route_identity(event.source)+ # The wake runs as the committed human source; the producer's source, rebuilt from the route's+ # stored origin, only names the route. Its labels, first speaker and stored profile drift from+ # the latest committed turn, so compare the route both resolve to now (``_owner`` checked it).+ if (runner.session_store._generate_session_key(restored.source) != entry.session_keyor runner._adapter_for_source(restored.source) is not adapter):raise RuntimeStoreError('admission_conflict')provenance = deepcopy(envelope['provenance'])source = deepcopy(envelope['source'])# Never anchor the wake to the stale human message; ``to_dict`` already omits a null anchor.source.pop('message_id', None)+ if 'relay' in provenance:+ # The relay seal binds the source; restore_native verified it over the anchored source.+ from gateway.session_ingress_context import reseal_relay+ provenance = reseal_relay(adapter, source, provenance)# Producer timestamps and platform reply IDs change on retry. Neither belongs# in the identity/fingerprint of the same immutable completion.envelope = {'source': source, 'route': entry.session_key,diff --git a/gateway/session_ingress_context.py b/gateway/session_ingress_context.pyindex 3370a970b9a..f75f9edfb8f 100644--- a/gateway/session_ingress_context.py+++ b/gateway/session_ingress_context.py@@ -58,6 +58,15 @@ def _relay_seal(transport, source, provenance):hashlib.sha256).hexdigest()+def reseal_relay(adapter, source, provenance):+ """*provenance* bound to the stored *source* dict instead; only for a seal the caller verified."""+ from gateway.session import SessionSource+ stored = SessionSource.from_dict(source)+ stored.is_bot = source['is_bot']+ base = {key: value for key, value in provenance.items() if key != 'relay'}+ return {**base, 'relay': _relay_seal(adapter._transport, stored, base)}++def register_transport_home(runner, profile, home):"""Called when the server creates a callback, never from event home fields."""homes = getattr(runner, '_native_transport_homes', None)diff --git a/tests/gateway/test_automation_notification_category.py b/tests/gateway/test_automation_notification_category.pyindex 3215135b529..7b083657c88 100644--- a/tests/gateway/test_automation_notification_category.py+++ b/tests/gateway/test_automation_notification_category.py@@ -202,11 +202,10 @@ async def test_native_completion_wake_admits_when_source_differs_only_by_message@pytest.mark.asyncio[email protected]('field', ['user_name', 'user_id', 'thread_id'])-async def test_native_completion_wake_refuses_other_source_drift(tmp_path, monkeypatch, field):+async def test_native_completion_wake_refuses_another_route(tmp_path, monkeypatch):_runner, authority, adapter, _source, metadata = await _native_owner(tmp_path, monkeypatch, 'human-1')try:- drifted = adapter.build_source(**{**_SOURCE, field: '7'})+ drifted = adapter.build_source(**_SOURCE, thread_id='7')event = MessageEvent(text='notice', source=drifted, internal=True, metadata=dict(metadata))with pytest.raises(RuntimeStoreError, match='admission_conflict'):await authority.admit_automation(adapter, event, 'notice')@@ -236,8 +235,8 @@ async def test_refused_watch_wake_logs_the_refusal_code(tmp_path, monkeypatch, crunner, authority, _adapter, source, metadata = await _native_owner(tmp_path, monkeypatch, 'human')try:route = metadata['gateway_session_key']- # Point the routing entry at a renamed user: the wake's source no longer matches the commit.- runner.session_store._entries[route].origin = replace_source(source, user_name='renamed')+ # Point the routing entry at another thread: the wake's source no longer names its route.+ runner.session_store._entries[route].origin = replace_source(source, thread_id='7')evt = {'type': 'completion', 'session_id': 'proc_x', 'session_key': route, 'platform': 'discord','chat_id': '42', 'chat_type': 'dm', 'exit_code': 0, 'output': 'done', 'started_at': 1.0,'parent_session_id': metadata['gateway_session_id']}diff --git a/tests/gateway/test_automation_wake_route.py b/tests/gateway/test_automation_wake_route.pynew file mode 100644index 00000000000..9fbab1a748b--- /dev/null+++ b/tests/gateway/test_automation_wake_route.py@@ -0,0 +1,94 @@+"""A producer wake enters its route as the committed human turn, whatever the route's stored origin+says about labels and speakers, from a subagent's process, and over the relay."""+import asyncio++import pytest++from gateway.config import Platform, PlatformConfig+from gateway.platforms.event import MessageEvent+from gateway.session import SessionSource+from gateway.session_identity import replace_source+from hermes_state_runtime import get_session_admission, list_session_admissions+from tests.gateway.test_automation_compression_media import _admit_human, _discord_owner+from tests.gateway.test_automation_notification_category import _authority, _native_owner++[email protected]('drift', [{'chat_name': 'renamed thread'}, {'user_name': None},+ {'user_id': '7'}, {'profile': 'work'}])+async def test_wake_admits_as_the_committed_turn_when_the_origin_drifted(tmp_path, monkeypatch, drift):+ runner, authority, _adapter, source, metadata = await _native_owner(tmp_path, monkeypatch, 'human-1')+ try:+ route, sid = metadata['gateway_session_key'], metadata['gateway_session_id']+ runner.session_store._entries[route].origin = replace_source(source, **drift)+ evt = {'type': 'completion', 'session_id': 'proc_x', 'session_key': route, 'platform': 'discord',+ 'chat_id': '42', 'chat_type': 'dm', 'exit_code': 0, 'output': 'done', 'started_at': 1.0,+ 'parent_session_id': sid}+ assert await runner._inject_watch_notification('[done]', evt) is True+ rows = list_session_admissions(authority.db, session_id=authority.logical_owner(sid), pending_only=False)+ human, wake = rows[0]['payload']['native_text_v1'], rows[-1]['payload']['native_text_v1']+ assert wake['source'] == {k: v for k, v in human['source'].items() if k != 'message_id'}+ assert wake['provenance'] == human['provenance']+ finally:+ authority.db.close()+++async def test_subagent_process_notice_enters_its_parent_route_but_not_after_reset(tmp_path, monkeypatch):+ runner, _, authority, source = await _discord_owner(tmp_path, monkeypatch)+ root = (await _admit_human(runner, authority, MessageEvent(text='human', source=source, message_id='human'))).ref.session_id+ key = runner.session_store._generate_session_key(source)+ worker, nested = root + '-worker', root + '-nested'+ authority.db.create_session(worker, source='subagent', parent_session_id=root)+ authority.db.create_session(nested, source='subagent', parent_session_id=worker)+ event = {'type': 'completion', 'session_id': 'proc-worker', 'started_at': 1,+ 'session_key': key, 'parent_session_id': nested}+ assert await runner._inject_watch_notification('worker-finished', event) is True+ rows = list_session_admissions(authority.db, session_id=root, pending_only=False)+ assert len(rows) == 2 and 'worker-finished' in rows[-1]['payload']['text']+ runner.session_store.reset_session(key)+ # A notice pinned to a session /new closed is dropped, never admitted to the fresh one.+ stale = dict(event, session_id='proc-old-worker')+ assert await runner._inject_watch_notification('old-worker', stale) is None+ await asyncio.sleep(0)+++def _relay_adapter():+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.ws_transport import WebSocketRelayTransport+ descriptor = CapabilityDescriptor(1, 'relay', 'Fixture', 4096, False, True, False, 'plain', 'chars')+ transport = WebSocketRelayTransport('http://127.0.0.1:1/relay', 'relay', '',+ gateway_id='fixture-gateway', upgrade_secret='fixture-secret')+ transport._ws = object() # the connector proof requires a live socket+ transport._descriptors_by_platform['relay'] = descriptor+ return RelayAdapter(PlatformConfig(), descriptor, transport=transport), transport+++def _relay_source(message_id=None):+ return SessionSource(platform=Platform.RELAY, chat_id='hub', chat_type='group', user_id='alex',+ message_id=message_id, delivered_via_upstream_relay=True)+++async def test_relay_wake_row_reverifies_the_source_it_stores(tmp_path, monkeypatch):+ from gateway.session_envelope import restore_native+ from gateway.session_ingress_context import native_callback, register_transport_home, relay_callback+ runner, authority = await _authority(tmp_path, monkeypatch)+ adapter, transport = _relay_adapter()+ runner.adapters = {Platform.RELAY: adapter}+ runner._wire_adapter_handlers(adapter)+ register_transport_home(runner, None, tmp_path)+ try:+ human = MessageEvent(text='human', source=_relay_source('human-1'), message_id='human-1')+ with native_callback(runner, human, tmp_path), relay_callback(transport, human):+ await authority.admit_native(human)+ route = runner.session_store._generate_session_key(human.source)+ event = MessageEvent(text='notice', source=_relay_source(), internal=True, metadata={+ 'gateway_session_key': route, 'gateway_session_id': runner.session_store.peek_session_id(route)})+ row = get_session_admission(authority.db, admission_id=(+ await authority.admit_automation(adapter, event, 'notice')).admission_id)+ assert row is not None+ assert restore_native(row['payload'], runner).source.message_id is None+ finally:+ authority.db.close()