The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): close a discarded lost turn so it never merges into the follower request
Teknium0fba8e4b5ddc
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 0ad4e3e00bc..7c26f33336b 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -371,6 +371,10 @@ class SessionAuthority:await self.receipt(actor, ref, admission_id)row = resolve_unknown_session_input(self.db, epoch=self.epoch, admission_id=admission_id,generation=generation)+ # Before the follower is scheduled: its request must not carry the discarded text merged in.+ from gateway.session_local_recovery import transcript_target+ from gateway.session_results import close_discarded_turn+ close_discarded_turn(self.db, transcript_target(self, ref))self._publish_pending(ref)self._schedule(ref)return self._receipt(row)diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex 087c5c1bd59..8fecb9aa48d 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -108,15 +108,18 @@ def restore_local_session(authority, sid):return SessionRef(authority.profile_id, sid)-def local_history(authority, ref):- """Display history from the current physical transcript; *ref* stays the logical root."""+def transcript_target(authority, ref):+ """The current physical transcript of logical *ref* (a local receipt's entry, else the tip)."""live = authority.sessions[ref.session_id]if live.source is not None and live.source.platform == Platform.LOCAL:restore_local_session(authority, ref.session_id)- target = local_receipt(authority.db, ref.session_id)['entry']['session_id']- else:- target = authority.physical_target(ref)- return authority.db.get_messages_as_conversation(target)+ return local_receipt(authority.db, ref.session_id)['entry']['session_id']+ return authority.physical_target(ref)+++def local_history(authority, ref):+ """Display history from the current physical transcript; *ref* stays the logical root."""+ return authority.db.get_messages_as_conversation(transcript_target(authority, ref))def reopen_local_session(authority, ref):diff --git a/gateway/session_results.py b/gateway/session_results.pyindex 0e747cb3d8c..8edc1936ae7 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -68,3 +68,20 @@ def admission_result(db, admission_id):saved = conn.execute('SELECT value FROM state_meta WHERE key=?',(_RESULT_PREFIX + admission_id,)).fetchone()return json.loads(saved[0]) if saved else None+++def close_discarded_turn(db, target_id):+ """Close a discarded ``unknown`` turn the way a failed turn is closed.++ The lost input stays in the transcript for the user to resend, but an open ``user`` tail would be+ merged into the follower's provider request by consecutive-user repair, re-sending the discarded+ turn as context. A Hermes-authored boundary (``display_kind=failed_turn``, stripped of its type+ before the wire) ends it. Its side effects are unknown, so the hedged copy. Idempotent on the+ durable tail, like the gateway and core failed-turn closers."""+ if db.latest_conversation_role(target_id) != 'user':+ return False+ import time+ from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, PARTIAL_FAILED_TURN_NOTICE+ db.append_message(target_id, 'assistant', PARTIAL_FAILED_TURN_NOTICE, timestamp=time.time(),+ display_kind=FAILED_TURN_DISPLAY_KIND)+ return Truediff --git a/tests/gateway/test_authority_unknown_resolution.py b/tests/gateway/test_authority_unknown_resolution.pyindex fb1bbbb6815..5d1a8c293d1 100644--- a/tests/gateway/test_authority_unknown_resolution.py+++ b/tests/gateway/test_authority_unknown_resolution.py@@ -118,3 +118,46 @@ async def test_resolve_unknown_is_fenced_by_generation_and_capability(tmp_path,await owner.close()await reader.close()store.close_all_db_handles()+++async def test_discarded_lost_turn_is_closed_and_never_merged_into_the_follower_request(tmp_path, monkeypatch):+ """Discard keeps the lost text visible for resending, but the next provider request must not+ glue it onto the follower (consecutive-user merge): it is closed like a failed turn."""+ from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, PARTIAL_FAILED_TURN_NOTICE+ from run_agent import AIAgent+ from tests.acp_adapter.test_failed_turn_closure import _LoopbackProvider+ monkeypatch.setenv('HERMES_DISABLE_PLUGINS', '1')+ monkeypatch.setenv('NO_PROXY', '127.0.0.1,localhost')+ store, authority, ref, unknown, follower = await _restarted_owner_with_unknown_head(tmp_path, monkeypatch, [])+ db = authority.db+ db.append_message('s', 'user', 'HEAD lost in restart') # the lost turn's turn-start flush+ viewer = AuthorityConnection(authority, Peer(), {'user_id': 'human'})+ provider = _LoopbackProvider()+ try:+ await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ reply = await viewer.dispatch({'id': 2, 'method': 'prompt.resolve_unknown', 'params': {+ 'session_id': 's', 'admission_id': unknown['admission_id'],+ 'execution_generation': unknown['generation']}})+ assert reply['result']['outcome'] == 'interrupted', reply+ await authority.sessions['s'].task+ rows = [m for m in db.get_messages('s') if m['role'] in ('user', 'assistant')]+ assert [(m['role'], m['content']) for m in rows[:2]] == [+ ('user', 'HEAD lost in restart'), ('assistant', PARTIAL_FAILED_TURN_NOTICE)]+ assert rows[1]['display_kind'] == FAILED_TURN_DISPLAY_KIND+ # The follower's real provider request, built from the live-replay transcript.+ history = [m for m in store.load_transcript('s') if m.get('content') != 'ACK_FOLLOWER'+ and m.get('content') != 'FOLLOWER']+ provider.script.extend({'finish_reason': 'stop', 'content': 'ok'} for _ in range(4))+ agent = AIAgent(api_key='fixture-only', base_url=provider.base_url, provider='openai-compat',+ model='fixture-model', max_iterations=2, enabled_toolsets=[], quiet_mode=True,+ skip_context_files=True, skip_memory=True, save_trajectories=False, platform='cli')+ await asyncio.to_thread(agent.run_conversation, 'FOLLOWER', conversation_history=history)+ chat = [r for r in provider.requests if 'messages' in r]+ sent = [m for m in chat[0]['messages'] if m['role'] != 'system']+ assert [m['content'] for m in sent if m['role'] == 'user'] == ['HEAD lost in restart', 'FOLLOWER'], sent+ assert sent[1] == {'role': 'assistant', 'content': PARTIAL_FAILED_TURN_NOTICE}+ finally:+ provider.shutdown()+ await viewer.close()+ store.close_all_db_handles()diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex b864c62b373..1e4d1b923f2 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -76,7 +76,9 @@ the follower runs exactly once. The generation must be the one stamped on the unrow (visible in the resume/`session.info` projection), so a stale or already-resolvedrow is refused with `stale_generation`. Desktop shows such a row in the queue panel as"Turn lost during restart" with a **Discard** button; the gateway CLI exposes it as-`/discard <admission_id>`. The lost input stays in the transcript for the user to resend.+`/discard <admission_id>`. The lost input stays in the transcript for the user to resend; the+discard closes it with a Hermes notice (like a failed turn), so it is never merged into the+follower's model request.A messaging user (Telegram, Discord, ...) whose session is paused this way is told once perpause episode, through the adapter's ordinary reply path, that the conversation is paused and