The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Kanban wakes and /loop ticks commit to the authority FIFO
Teknium5a0c8bac4b11
diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex 493e0d7d01c..4ef9c486bac 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -454,7 +454,11 @@ class GatewayGoalsMixin:mgr.state.ticks_fired if mgr.state else "?",platform_name, source.chat_id, source.thread_id,)- await adapter.handle_message(self._synthetic_prompt_event(source, wakeup, internal=True))+ from gateway.session_automation import admit_route_wake+ # Under a session authority the tick commits to the FIFO (never a classic turn beside an+ # admitted one); a slash-command loop is a command and keeps the command path.+ if wakeup.lstrip().startswith("/") or not await admit_route_wake(self, adapter, source, wakeup, "loop-tick"):+ await adapter.handle_message(self._synthetic_prompt_event(source, wakeup, internal=True))# Slash-command loops dispatch through the command path and never hit the post-turn# completion hook — complete the tick immediately (caps + scheduling).if wakeup.lstrip().startswith("/"):diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 4156596e645..55a2d6347ba 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -725,6 +725,11 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)"""Fast-path while this session's agent is running: interrupt by default (minimal latency);busy_input_mode queue/steer, subagent and compression protection demote to queue."""from gateway.run import _AGENT_PENDING_SENTINEL+ if getattr(event, "internal", False) and not event.get_command():+ # Main's rule (run_busy's busy handler, which the shared runtime's busy dispatch skips):+ # an internal synthetic event never interrupts or steers the running turn.+ self._queue_or_replace_pending_event(_quick_key, event)+ return None_handled, _result = await self._hm_busy_slash_or_photo(event, source, _quick_key)if _handled:return _resultdiff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 60bdd726449..848d8c31a59 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -219,3 +219,36 @@ async def admit_automation(authority, adapter, event, identity):session_id=ref.session_id, request_id=identity, payload=deepcopy(payload),_authorize_write=authority._admission_gate()), then=partial(authority._admitted, ref, event), ordered=True,after=partial(authority._schedule_admitted, ref))+++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 the+ authority FIFO, like heartbeats and process completions, instead of a classic turn that+ interrupts or races the admitted one. ``False`` when no authority serves the scope or the+ route holds no committed human turn to borrow provenance from: the caller keeps the adapter+ path (nothing is queued there either). Raises ``RuntimeStoreError`` on a refusal."""+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ key = runner._session_key_for_source(source)+ entry = runner.session_store.lookup_by_session_key(key) if authority is not None else None+ if entry is None or source.platform == Platform.LOCAL:+ return False+ from gateway.session_envelope import restore_native+ from hermes_state_runtime import list_session_admissions+ prior = list_session_admissions(authority.db, session_id=authority.logical_owner(entry.session_id),+ pending_only=False)+ envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)+ if 'native_text_v1' in r['payload']), None)+ if envelope is None or 'provenance' not in envelope:+ return False+ # The route's committed source, which ``snapshot_automation`` re-derives and compares.+ restored = restore_native({'text': text, 'native_text_v1': {+ k: v for k, v in envelope.items() if k != 'media'}}, runner)+ import uuid+ identity = json.dumps([producer, key, uuid.uuid4().hex], separators=(',', ':'))+ event = MessageEvent(text=text, message_type=MessageType.TEXT, source=restored.source, internal=True,+ message_id=identity, metadata={'gateway_session_key': key,+ 'gateway_session_id': entry.session_id,+ **(metadata or {})})+ await authority.admit_automation(adapter, event, identity)+ return Truediff --git a/gateway/wake.py b/gateway/wake.pyindex a0273ede7f1..fc7d8d4ad20 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -100,6 +100,16 @@ async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source:if source is None:raise ValueError("deliver_wake: push-capable adapter requires a SessionSource")from gateway.platforms.event import MessageEvent, MessageType+ runner = getattr(adapter, "gateway_runner", None)+ if runner is not None:+ from gateway.session_automation import admit_route_wake+ from hermes_state_runtime import RuntimeStoreError+ category = {"notification_category": notification_category} if notification_category != "result" else {}+ try:+ if await admit_route_wake(runner, adapter, source, text, "kanban-wake", category):+ return # committed to the session FIFO: never interrupts the admitted turn+ except RuntimeStoreError as exc:+ raise WakeNotAccepted(str(exc)) from excsynth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True,metadata={"notification_category": notification_category})await admit_internal_event(adapter, synth_event)diff --git a/tests/gateway/test_internal_wake_never_interrupts.py b/tests/gateway/test_internal_wake_never_interrupts.pynew file mode 100644index 00000000000..0871a7cd2e9--- /dev/null+++ b/tests/gateway/test_internal_wake_never_interrupts.py@@ -0,0 +1,158 @@+"""An internal wake never interrupts or steers an admitted user turn (N44, sequence 1).++Main's busy handler queued every internal synthetic event (Kanban wakes, /loop ticks, process+notifications) behind the running turn. Under the session authority a busy adapter hands every+non-command to ``dispatch_shared_busy``; the authority declines internal input, so the wake fell+through to the classic busy path, which in the default ``interrupt`` mode ended the user's turn.+Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over SQLite; the user turn is a+stand-in holding a real running-agent slot.+"""+import asyncio++import pytest+++async def test_kanban_wake_during_an_admitted_turn_queues_without_interrupting(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_results import execution_result+ from gateway.wake import deliver_wake+ 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))+ sent = []++ async def send(chat_id, content, reply_to=None, metadata=None):+ sent.append(content)+ return SendResult(success=True, message_id=f's{len(sent)}')+ monkeypatch.setattr(adapter, 'send', send)+ adapter.gateway_runner = runner # as GatewayRunner._create_adapter binds every adapter+ 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()+ interrupts, executed = [], []++ class Agent:+ def interrupt(self, message=None, *args, **kwargs):+ interrupts.append(message)++ async def turn(event, source, quick_key, run_generation):+ executed.append(event.text)+ if event.text == 'A':+ runner._session_state(quick_key).turn.agent = Agent() # the built, running agent+ running.set()+ await finish.wait()+ captured = execution_result.get()+ if captured is not None:+ captured['result'] = {'final_response': 'reply ' + event.text, 'messages': []}+ return 'reply ' + event.text+ 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)+ wake = '[Kanban task completed] t_1'+ await asyncio.wait_for(deliver_wake(adapter, text=wake, source=source), 10) # accepted, no raise+ assert interrupts == [], 'the internal wake interrupted the admitted user turn'+ finish.set()+ async with asyncio.timeout(10):+ while wake not in executed:+ await asyncio.sleep(0.01)+ owner = runner.session_store.peek_session_id(key)++ def rows():+ return list_session_admissions(authority.db, session_id=owner, pending_only=False)+ async with asyncio.timeout(10):+ while [r['status'] for r in rows()] != ['terminal', 'terminal']:+ await asyncio.sleep(0.01)+ # The wake ran as its own FIFO turn after the user's, never inside or instead of it.+ assert [(r['principal_id'].split(':')[0], r['outcome']) for r in rows()] == [+ ('messaging', 'completed'), ('automation', 'completed')]+ assert executed == ['A', wake]+++async def test_idle_loop_tick_runs_as_a_fifo_turn_not_beside_it(monkeypatch):+ """N44 sequence 2: an idle /loop tick started a classic turn outside the FIFO, so a drain+ claiming a user row meanwhile handed that row's text to the tick's turn and settled it+ ``completed`` without running it. The tick must commit as its own FIFO admission."""+ from types import SimpleNamespace++ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_ingress import executing_admission+ from gateway.session_results import execution_result+ from hermes_cli import loops+ 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))+ adapter.gateway_runner = runner++ async def send(chat_id, content, reply_to=None, metadata=None):+ from gateway.platforms.base import SendResult+ return SendResult(success=True, message_id='sent')+ monkeypatch.setattr(adapter, 'send', send)+ 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)+ started = []++ async def turn(event, source, quick_key, run_generation):+ started.append((event.text, executing_admission.get()))+ captured = execution_result.get() # None outside the drain+ if captured is not None:+ captured['result'] = {'final_response': 'ok', 'messages': []}+ return 'ok'+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)+ await adapter.handle_message(MessageEvent(text='hello', source=source, message_id='m1'))++ def rows():+ owner = runner.session_store.peek_session_id(key)+ return list_session_admissions(authority.db, session_id=owner, pending_only=False) if owner else []+ async with asyncio.timeout(10):+ while [r['status'] for r in rows()] != ['terminal'] or runner._is_session_running(key):+ await asyncio.sleep(0.01)+ owner = runner.session_store.peek_session_id(key)++ class Loop:+ state = SimpleNamespace(ticks_fired=1)++ def __init__(self, session_id=None):+ pass++ def is_due(self, now):+ return True++ def fire_tick(self):+ return 'loop tick prompt'++ def abandon_tick(self):+ raise AssertionError('the tick was not admitted')+ monkeypatch.setattr(loops, 'LoopManager', Loop)+ monkeypatch.setattr(loops, 'goal_blocks_loop_tick', lambda sid: False)+ route = {'platform': 'discord', 'chat_id': '42', 'chat_type': 'dm', 'user_id': '42'}+ await runner._loop_wakeup_fire_one(owner, SimpleNamespace(awaiting_response=False, next_due_at=0, route=route),+ 1e12, set())+ async with asyncio.timeout(10):+ while len(started) < 2:+ await asyncio.sleep(0.01)+ assert started == [('hello', True), ('loop tick prompt', True)], 'the tick ran outside the FIFO'+ async with asyncio.timeout(10):+ while [r['status'] for r in rows()] != ['terminal', 'terminal']:+ await asyncio.sleep(0.01)