The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(runtime): persist diagnostic automation category through replay
David Dudok de Witbdac7911d99e
diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 536ada2e5ea..62278707b68 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -56,6 +56,13 @@ def _owner(runner, event):return entry+def automation_notification_metadata(metadata):+ """Validate trusted producer category; omit the default from old fingerprints."""+ category = metadata.get('notification_category', 'result')+ if category not in ('result', 'diagnostic'):+ raise RuntimeStoreError('invalid_params')+ return {'notification_category': category} if category == 'diagnostic' else {}+# notification_origin / original_trigger_message_id are producer debug context (#52694) and are not# persisted; notification_category="diagnostic" rides the snapshot so the replayed wake still mutes._AUTOMATION_METADATA = frozenset({'gateway_session_key', 'gateway_session_id', 'automation_identities',@@ -67,9 +74,9 @@ def snapshot_automation(authority, adapter, event, identity):if (not event.internal or event.message_type != MessageType.TEXT or event.is_command()or not isinstance(event.text, str) or not identityor event.media_urls or event.prompt_response or event.source.platform == Platform.API_SERVER- or set(event.metadata) - _AUTOMATION_METADATA- or event.metadata.get('notification_category', 'diagnostic') != 'diagnostic'):+ or set(event.metadata) - _AUTOMATION_METADATA):raise RuntimeStoreError('invalid_params')+ notification = automation_notification_metadata(event.metadata)entry = _owner(runner, event)if event.source.platform == Platform.LOCAL:return snapshot_local_automation(authority, adapter, event, identity, entry)@@ -94,13 +101,12 @@ def snapshot_automation(authority, adapter, event, identity):'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),'event': {'message_id': identity}, 'provenance': provenance,'automation': {'identity': identity, 'owner': entry.session_id}}+ envelope['automation'].update(notification)if getattr(event, '_heartbeat_session_id', None):envelope['automation']['heartbeat'] = event._heartbeat_session_ididentities = event.metadata.get('automation_identities')if identities:envelope['automation']['identities'] = sorted(set(identities))- if event.metadata.get('notification_category'):- envelope['automation']['notification_category'] = 'diagnostic'return {'text': event.text, 'native_text_v1': envelope}, entry@@ -125,6 +131,7 @@ def snapshot_local_automation(authority, adapter, event, identity, entry):raise RuntimeStoreError('permission_denied')descriptor = {'identity': identity, 'owner': ref.session_id,'route': entry.session_key, 'target': entry.session_id}+ descriptor.update(automation_notification_metadata(event.metadata))if event.metadata.get('turn_author') is not None:from agent.turn_author import parse_turn_authordescriptor['turn_author'] = parse_turn_author(event.metadata['turn_author'])@@ -134,8 +141,6 @@ def snapshot_local_automation(authority, adapter, event, identity, entry):descriptor['identities'] = sorted(set(event.metadata['automation_identities']))if getattr(event, '_heartbeat_session_id', None):descriptor['heartbeat'] = event._heartbeat_session_id- if event.metadata.get('notification_category'):- descriptor['notification_category'] = 'diagnostic'return {'text': event.text, 'local_automation_v1': descriptor}, entry@@ -163,12 +168,11 @@ def restore_local_automation(authority, ref, row):event = MessageEvent(text=row['payload']['text'], source=live.source, internal=True,message_id=descriptor['identity'], metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})+ event.metadata.update(automation_notification_metadata(descriptor))if descriptor.get('turn_author') is not None:event.metadata['turn_author'] = deepcopy(descriptor['turn_author'])if descriptor.get('heartbeat'):event._heartbeat_session_id = descriptor['heartbeat']- if descriptor.get('notification_category') == 'diagnostic':- event.metadata['notification_category'] = 'diagnostic'return eventdiff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex dbd8fdb8eeb..fdb813c1945 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -200,7 +200,8 @@ async def _migrate(authority, actor, home, root):_write(path, record)continueawait _admit(authority, actor, home, root, _delivery_id(record['delivery_id']),- record['message'], ref, live, entry, author=parse_turn_author(record.get('author')), legacy=record)+ record['message'], ref, live, entry, author=parse_turn_author(record.get('author')), legacy=record,+ notification_category=record.get('notification_category', 'result'))async def recover_bot_deliveries(authority):@@ -245,8 +246,11 @@ def _watch_reply(authority, home, key, admission_id):async def deliver(connection, params):authority, actor = connection.authority, connection.actorhome = _home(authority, actor, params.get('profile'))- if set(params) - {'id', 'profile', 'message', 'session_id', 'author'}:+ if set(params) - {'id', 'profile', 'message', 'session_id', 'author', 'notification_category'}:raise RuntimeStoreError('invalid_params')+ from gateway.session_automation import automation_notification_metadata+ notification = automation_notification_metadata(params)+ category = notification.get('notification_category', 'result')try:key = _delivery_id(params.get('id'))except ValueError as exc:@@ -263,7 +267,8 @@ async def deliver(connection, params):record = _read(path)if record is not None and record.get('admission_id'):if (record['message'] != message or record['principal_id'] != actor.subject- or record.get('author') != author):+ or record.get('author') != author+ or record.get('notification_category', 'result') != category):raise RuntimeStoreError('admission_conflict')authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')return _result(authority, record)@@ -271,7 +276,8 @@ async def deliver(connection, params):record = _read(path)if record is not None and record.get('admission_id'):if (record['message'] != message or record['principal_id'] != actor.subject- or record.get('author') != author):+ or record.get('author') != author+ or record.get('notification_category', 'result') != category):raise RuntimeStoreError('admission_conflict')authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')return _result(authority, record)@@ -280,20 +286,26 @@ async def deliver(connection, params):ref, live, entry = _target(authority, actor)if params.get('session_id', entry.session_id) != entry.session_id:raise RuntimeStoreError('admission_conflict')- return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author)+ return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,+ notification_category=category)-async def _admit(authority, actor, home, root, key, message, ref, live, entry, author=None, legacy=None):+async def _admit(authority, actor, home, root, key, message, ref, live, entry, author=None, legacy=None,+ notification_category='result'):+ from gateway.session_automation import automation_notification_metadata+ notification = automation_notification_metadata({'notification_category': notification_category})path = root / f'{key}.json'event = MessageEvent(text=message, source=live.source, internal=True,message_id='bot:' + key, metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})+ event.metadata.update(notification)if author is not None:event.metadata['turn_author'] = dict(author)# Pin the physical target before committing. A process death in this# two-store window leaves an explicit unknown record, never a new target.record = dict(legacy or {}, delivery_id=key, profile_home=str(home), session_id=ref.session_id,principal_id=actor.subject, message=message, status='ambiguous')+ record.update(notification)if author is not None:record['author'] = dict(author)_write(path, record)diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex 0cc27fb85e7..826520edd37 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -151,8 +151,8 @@ def restore_native(payload, runner=None):event._heartbeat_session_id = envelope['automation']['heartbeat']event.metadata = {'gateway_session_key': envelope['route'],'gateway_session_id': envelope['automation']['owner']}- if envelope['automation'].get('notification_category') == 'diagnostic':- event.metadata['notification_category'] = 'diagnostic'+ from gateway.session_automation import automation_notification_metadata+ event.metadata.update(automation_notification_metadata(envelope['automation']))return eventdiff --git a/tests/gateway/test_automation_notification_category.py b/tests/gateway/test_automation_notification_category.pynew file mode 100644index 00000000000..5953a594466--- /dev/null+++ b/tests/gateway/test_automation_notification_category.py@@ -0,0 +1,135 @@+"""Diagnostic-only metadata survives the canonical FIFO, without inference."""+from types import SimpleNamespace++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.event import MessageEvent+from gateway.run import GatewayRunner+from gateway.session_authority import SessionAuthority, initialize_session_authority+from gateway.session_contract import Principal+from hermes_state_runtime import RuntimeStoreError, get_session_admission, list_session_admissions+++async def _authority(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ monkeypatch.setattr('gateway.session_bot._watch_reply', lambda *args: None)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ from hermes_state import SessionDB+ db = SessionDB(tmp_path / 'state.db')+ runner.session_store._db = db+ runner._session_db = db+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='category-fixture',+ db=db)+ return runner, authority+++def test_live_delivery_forwards_diagnostic_category(tmp_path, monkeypatch):+ from tools import bot_live_delivery as live+ calls = []+ monkeypatch.setattr(live, 'authority_delivery', lambda home, params: calls.append(params) or {})+ owner = dict(profile_home=str(tmp_path), session_id='bot', canonical=True,+ lease_id='fixture', live_session_id='bot')+ live.deliver_to_live_owner(tmp_path, owner, 'warning', notification_category='diagnostic')+ assert calls[0]['notification_category'] == 'diagnostic'++[email protected]('category', ['result', 'diagnostic'])+async def test_bot_category_is_committed_restored_and_part_of_retry_identity(tmp_path, monkeypatch, category):+ from gateway.session_bot import deliver+ from gateway.session_local import create_local_session+ from gateway.session_local_title import title_new_session+ from gateway.session_automation import restore_local_automation+ runner, authority = await _authority(tmp_path, monkeypatch)+ actor = Principal('test-owner', 'default', frozenset({'session:create', 'session:submit', 'session:read'}), 'fixture')+ try:+ ref = create_local_session(authority, actor, dict(request_id='bot', source='gui', model='fixture', toolsets=[]))+ title_new_session(authority, ref, 'Bot Chat')+ connection = SimpleNamespace(authority=authority, actor=actor)+ params = dict(id='a' * 32, profile='default', message='notice', notification_category=category)+ first = await deliver(connection, params)+ retry = await deliver(connection, params)+ assert first['admission_id'] == retry['admission_id']+ # Re-open the actual on-disk receipt through the production readback+ # helper; substitute only transport, then exercise the real owner gate.+ from tools import bot_live_delivery as live+ monkeypatch.setattr(live, 'authority_delivery', lambda home, request: request)+ replay = live.read_delivery_result(tmp_path, params['id'])+ assert replay is not None+ assert replay.get('notification_category', 'result') == category+ assert (await deliver(connection, replay))['admission_id'] == first['admission_id']+ row = get_session_admission(authority.db, admission_id=first['admission_id'])+ assert row is not None+ descriptor = row['payload']['local_automation_v1']+ restored = restore_local_automation(authority, ref, row)+ if category == 'diagnostic':+ assert descriptor['notification_category'] == 'diagnostic'+ assert restored.metadata['notification_category'] == 'diagnostic'+ else:+ assert 'notification_category' not in descriptor+ assert 'notification_category' not in restored.metadata+ # Omitted default retains the old request fingerprint.+ assert (await deliver(connection, {k: v for k, v in params.items() if k != 'notification_category'}))['admission_id'] == first['admission_id']+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ await deliver(connection, {**params, 'notification_category': 'result' if category == 'diagnostic' else 'diagnostic'})+ assert len(list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)) == 1+ finally:+ authority.db.close()++[email protected]('category', [None, [], {}, 'other'])+async def test_bot_invalid_category_refuses_before_admission(tmp_path, monkeypatch, category):+ from gateway.session_bot import deliver+ runner, authority = await _authority(tmp_path, monkeypatch)+ actor = Principal('test-owner', 'default', frozenset({'session:submit'}), 'fixture')+ try:+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await deliver(SimpleNamespace(authority=authority, actor=actor),+ dict(id='a' * 32, profile='default', message='notice', notification_category=category))+ assert authority.db.get_session_by_title('Bot Chat') is None+ finally:+ authority.db.close()++[email protected]('category', ['result', 'diagnostic'])+async def test_native_automation_category_roundtrip(tmp_path, monkeypatch, category):+ from gateway.session_ingress_context import native_callback, register_transport_home+ from gateway.session_envelope import restore_native+ from plugins.platforms.discord.adapter import DiscordAdapter+ runner, authority = await _authority(tmp_path, monkeypatch)+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))+ runner.adapters = {Platform.DISCORD: adapter}+ runner._wire_adapter_handlers(adapter)+ register_transport_home(runner, None, tmp_path)+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')+ human = MessageEvent(text='human', source=source, message_id='human')+ try:+ with native_callback(runner, human, tmp_path):+ await authority.admit_native(human)+ route = runner.session_store._generate_session_key(source)+ sid = runner.session_store.peek_session_id(route)+ event = MessageEvent(text='notice', source=source, internal=True,+ metadata={'gateway_session_key': route, 'gateway_session_id': sid, 'notification_category': category,+ 'notification_origin': 'process_registry_synthetic',+ 'original_trigger_message_id': 'producer-context'})+ receipt = await authority.admit_automation(adapter, event, 'notice')+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ assert row is not None+ descriptor = row['payload']['native_text_v1']['automation']+ restored = restore_native(row['payload'], runner)+ assert restored.internal+ assert descriptor.get('notification_category', 'result') == category+ assert restored.metadata.get('notification_category', 'result') == category+ assert 'notification_origin' not in descriptor+ assert 'original_trigger_message_id' not in descriptor+ if category == 'result':+ assert 'notification_category' not in descriptor+ event.metadata.pop('notification_category')+ assert (await authority.admit_automation(adapter, event, 'notice')).admission_id == receipt.admission_id+ finally:+ authority.db.close()diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex f01712b85e2..9f02b3d4ff9 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -236,11 +236,14 @@ def deliver_to_live_owner(pinned = _owner(profile_home, owner)if not isinstance(message, str):raise ValueError("message must be a string")+ if notification_category not in ('result', 'diagnostic'):+ raise ValueError("invalid notification category")home = Path(profile_home).resolve()return authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),profile=home.name if home.parent.name == "profiles" else "default",message=message, **({"session_id": pinned["session_id"]} if pinned["session_id"] else {}),- **({"author": dict(author)} if author else {})))+ **({"author": dict(author)} if author else {}),+ **({"notification_category": "diagnostic"} if notification_category == "diagnostic" else {})))def claim_pending_delivery(profile_home, owner):@@ -282,10 +285,12 @@ def read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[strrecord = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")if record is not None and record.get('admission_id'):home = Path(profile_home).resolve()- # The authority compares the stored author to the retry payload; omitting it is a conflict.+ # Readback replays the immutable envelope; dropping category or author conflicts.return authority_delivery(home, dict(id=delivery_id,profile=home.name if home.parent.name == 'profiles' else 'default', message=record['message'],- **({'author': dict(record['author'])} if record.get('author') else {})))+ **({'author': dict(record['author'])} if record.get('author') else {}),+ **({'notification_category': record['notification_category']}+ if 'notification_category' in record else {})))return record