The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): messaging /new carries a queued route wake to the fresh session
Teknium84446f61f65b
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 4ad15f6fec1..111c1840e4a 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -322,6 +322,8 @@ class GatewayTurnPersistenceMixin:elif agent_result.get("compression_exhausted") and session_entry and session_key:logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)new_entry = await self.async_session_store.reset_session(session_key)+ from gateway.session_automation import move_route_wakes+ await move_route_wakes(self, session_key, session_entry.session_id)self._evict_cached_agent(session_key)# Conversation boundary: the funnel clears every conversation-scoped per-session dict.self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex e62e5ae3178..1f1d74b24ab 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -225,6 +225,54 @@ async def admit_automation(authority, adapter, event, identity):after=partial(authority._schedule_admitted, ref))+_ROUTE_WAKE_PRODUCERS = frozenset({'kanban-wake', 'loop-tick'})+++async def move_route_wakes(runner, session_key, old_session_id):+ """After the route rotated (/new, /reset, compression-exhaustion reset), carry the old owner's+ still-queued route wakes to the fresh session, as main's #114456 kept a parked internal wake+ across /new. Left behind, the old drain refuses them (``admission_conflict``) and they stay+ queued forever. Completions pinned to the closed conversation are not moved (they fail closed,+ #55578), nor anything behind an ``unknown`` head (the operator's to resume)."""+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ entry = runner.session_store.lookup_by_session_key(session_key) if authority is not None else None+ if entry is None or not old_session_id:+ return+ import asyncio+ from functools import partial+ from gateway.session_authority import LiveSession+ from gateway.session_contract import Principal+ from gateway.session_runtime_workers import tracked_write+ from hermes_state_runtime import list_session_admissions+ old = SessionRef(authority.profile_id, authority.logical_owner(old_session_id))+ new = SessionRef(authority.profile_id, authority.logical_owner(entry.session_id))+ if old.session_id not in authority.sessions or old == new:+ return+ rows = await asyncio.to_thread(list_session_admissions, authority.db, session_id=old.session_id)+ if any(row['status'] == 'unknown' for row in rows):+ return+ actor = Principal('messaging-control', authority.profile_id, frozenset({'session:submit', 'session:control'}), 'reset')+ for row in rows:+ automation = row['payload'].get('native_text_v1', {}).get('automation', {})+ identity = json.loads(row['request_id']) if automation and row['request_id'].startswith('[') else None+ if (row['status'] != 'queued' or row['principal_id'] != 'automation:' + session_key+ or not isinstance(identity, list) or identity[:1] not in ([p] for p in _ROUTE_WAKE_PRODUCERS)):+ continue+ try:+ await authority.cancel_queued(actor, old, row['admission_id'])+ except RuntimeStoreError:+ continue # claimed meanwhile: it runs where it is+ payload = deepcopy(row['payload'])+ payload['native_text_v1']['automation']['owner'] = new.session_id+ authority.sessions.setdefault(new.session_id, LiveSession(authority.sessions[old.session_id].source, session_key))+ await tracked_write(authority, partial(+ admit_session_input, authority.db, epoch=authority.epoch, principal_id=row['principal_id'],+ session_id=new.session_id, request_id=row['request_id'], payload=payload,+ _authorize_write=authority._admission_gate()), then=partial(authority._admitted, new, None),+ ordered=True, after=partial(authority._schedule_admitted, new))++async def admit_route_wake(runner, adapter, source, text, producer, metadata=None):"""Commit a producer wake (Kanban push wake, /loop tick) for ``source``'s route into theauthority FIFO, like heartbeats and process completions, instead of a classic turn thatdiff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex e9b5c301208..6263960ec75 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -184,6 +184,8 @@ class GatewaySessionCommandsMixin:new_entry = await self.async_session_store.reset_session(session_key)_old_sid = old_entry.session_id if old_entry else None+ from gateway.session_automation import move_route_wakes+ await move_route_wakes(self, session_key, _old_sid) # main #114456: a parked wake survives /newawait self._fire_session_reset_hooks(source, session_key, _old_sid,new_entry.session_id if new_entry else None)# Scoped to the profile serving this source so a multiplexed /new banner reports thediff --git a/tests/gateway/test_new_moves_automation_wake.py b/tests/gateway/test_new_moves_automation_wake.pynew file mode 100644index 00000000000..6a151791acb--- /dev/null+++ b/tests/gateway/test_new_moves_automation_wake.py@@ -0,0 +1,67 @@+"""Messaging /new keeps a queued automation wake and runs it on the fresh session, as main's #114456+kept a parked internal wake across /new; it is never stranded queued on the abandoned owner (N83).+Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over SQLite; the turn is a stand-in."""+import asyncio++import pytest++from tests.waiting import async_wait_until+++async def test_new_moves_a_queued_wake_to_the_fresh_session(monkeypatch):+ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.base import SendResult+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_automation import admit_route_wake+ from gateway.session_results import execution_result+ from hermes_state_runtime import list_session_admissions+ from plugins.platforms.discord.adapter import DiscordAdapter++ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')+ runner = GatewayRunner(GatewayConfig())+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))++ async def send(chat_id, content, reply_to=None, metadata=None):+ return SendResult(success=True, message_id='sent')+ monkeypatch.setattr(adapter, 'send', send)+ adapter.gateway_runner = runner+ runner.adapters = {Platform.DISCORD: adapter}+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')+ runner._wire_adapter_handlers(adapter)+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')+ key = runner.session_store._generate_session_key(source)+ running, finish = asyncio.Event(), asyncio.Event()+ executed = []++ class Agent:+ def interrupt(self, *args, **kwargs):+ pass++ async def turn(event, source, quick_key, run_generation):+ executed.append((event.text, runner.session_store.peek_session_id(quick_key)))+ if event.text == 'A':+ runner._session_state(quick_key).turn.agent = Agent()+ running.set()+ await finish.wait()+ captured = execution_result.get()+ if captured is not None:+ captured['result'] = {'final_response': 'reply', 'messages': []}+ return 'reply'+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)++ await adapter.handle_message(MessageEvent(text='A', source=source, message_id='A'))+ await asyncio.wait_for(running.wait(), 10)+ old = runner.session_store.peek_session_id(key)+ assert await admit_route_wake(runner, adapter, source, 'WAKE', 'kanban-wake')+ await adapter.handle_message(MessageEvent(text='/new', source=source, message_id='new'))+ new = runner.session_store.peek_session_id(key)+ assert new != old+ finish.set()+ await async_wait_until(lambda: any(text == 'WAKE' for text, _ in executed), timeout=15,+ what='the wake to run after /new')+ rows = list_session_admissions(authority.db, session_id=old, pending_only=False)+ assert not [r for r in rows if r['status'] == 'queued'], rows+ assert [sid for text, sid in executed if text == 'WAKE'] == [new], 'the wake must run once, on the fresh session'