Skip to content

The agent that grows with you

fix(gateway): Discard closes a turn lost while parked on approval or clarify

Tekniuma8603c52de9c
diff --git a/gateway/session_results.py b/gateway/session_results.py
index 30b44f4a8ed..c76cd21dfb3 100644
--- a/gateway/session_results.py
+++ b/gateway/session_results.py
@@ -108,15 +108,20 @@ def close_discarded_turn(db, conn, row):
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. The boundary lands on
the CURRENT physical transcript (local reset/compression lineage tip), resolved on this
- connection. Idempotent on the durable tail, like the gateway and core failed-turn closers."""
+ connection. Idempotent on the durable tail, like the gateway and core failed-turn closers.
+
+ A turn lost while parked on a tool (an approval or clarify prompt) ends on its assistant
+ ``tool_calls`` row with no result. That tail is open too: repair prunes the unanswered call,
+ drops the now-empty row and merges the discarded input into the follower's user turn, so it
+ gets the same boundary (merged onto the call row, whose calls are then pruned)."""
import time
from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, PARTIAL_FAILED_TURN_NOTICE
from hermes_state_local_lineage import local_physical_target
from hermes_state_runtime import _canonical_chain
target = _canonical_chain(conn, local_physical_target(conn, row['target_session_id']))[-1]
- tail = conn.execute("SELECT role FROM messages WHERE session_id=? AND active=1 "
+ tail = conn.execute("SELECT role, tool_calls FROM messages WHERE session_id=? AND active=1 "
"AND role NOT IN ('session_meta','system') ORDER BY id DESC LIMIT 1", (target,)).fetchone()
- if tail is None or tail[0] != 'user':
+ if tail is None or not (tail[0] == 'user' or (tail[0] == 'assistant' and tail[1] not in (None, '', '[]'))):
return False
db._append_messages_in_transaction(conn, target, [{
'role': 'assistant', 'content': PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),
diff --git a/tests/gateway/test_unknown_receipt_boundaries.py b/tests/gateway/test_unknown_receipt_boundaries.py
index cd1774aec78..59045e1b60f 100644
--- a/tests/gateway/test_unknown_receipt_boundaries.py
+++ b/tests/gateway/test_unknown_receipt_boundaries.py
@@ -66,3 +66,28 @@ async def test_discard_closure_failure_keeps_unknown_fence_and_retry_is_exact(ow
owner.db.append_message(target, 'user', 'FOLLOWER')
assert await owner.resolve_unknown(actor, ref, first['admission_id'], claim['generation']) == settled
assert owner.db.latest_conversation_role(target) == 'user', 'retry closed a successor turn'
+
+
+async def test_discard_closes_turn_lost_while_parked_on_a_tool(owner, monkeypatch):
+ """A turn lost waiting on approval/clarify ends on an unanswered assistant ``tool_calls`` row.
+ Discard must close it too, or repair prunes the call, drops the empty row and merges the
+ discarded input into the follower's request."""
+ from agent.agent_runtime_helpers import repair_message_sequence
+ owner.db.create_session('s', source='test')
+ owner.sessions['s'] = LiveSession(None, 'route')
+ ref = SessionRef(owner.profile_id, 's')
+ actor = Principal('human', owner.profile_id, frozenset({'session:submit', 'session:control'}), 't')
+ first = admit_session_input(owner.db, epoch=owner.epoch, principal_id='human', session_id='s',
+ request_id='lost', payload={'text': 'LOST'})
+ claim = claim_session_input(owner.db, epoch=owner.epoch, session_id='s')
+ owner.db.append_message('s', 'user', 'LOST')
+ owner.db.append_message('s', 'assistant', '', tool_calls=[{'id': 'call_gate', 'type': 'function',
+ 'function': {'name': 'clarify', 'arguments': '{}'}}])
+ owner.epoch = begin_runtime_epoch(owner.db, instance_id='restart')
+ recover_session_inputs(owner.db, epoch=owner.epoch)
+ monkeypatch.setattr(owner, '_schedule', lambda ref: None)
+ await owner.resolve_unknown(actor, ref, first['admission_id'], claim['generation'])
+ history = owner.db.get_messages_as_conversation('s') + [{'role': 'user', 'content': 'FOLLOWER'}]
+ repair_message_sequence(None, history)
+ assert [m['content'] for m in history if m['role'] == 'user'] == ['LOST', 'FOLLOWER'], history