The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a returning handoff, a bot-minted Bot Chat and a damaged receipt after reset handoffs
Teknium53c86a8e8af1
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 3dcf5b92015..5113dcf8d80 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -275,7 +275,8 @@ class SessionAuthority:from gateway.config import Platformself._require_admission_open()live = self.sessions.get(sid)- took_over = live is None or live.route != route+ # *sid* takes the route over: new here, moved onto it, or back after another conversation had it.+ took_over = live is None or live.route != route or live.supersededif live is None:live = self.sessions[sid] = LiveSession(source, route)elif (live.source is not None and live.source.platform == Platform.LOCALdiff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 87b39c4af30..03cfd1a4f9f 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -357,20 +357,24 @@ async def _create_bot_chat(authority, actor, *, displace=None):def _bot_chat_creation_id(authority, actor):"""The first creation identity whose session is not spent. Generation 0 keeps the historical``bot-chat:<profile>`` id; a generation is spent once its session was deleted (retired: a retry- must never resurrect it) or renamed (titled, but not "Bot Chat" — or the lookup had found it),- and a replacement takes the next one. Derived from durable rows only, so a restart and two- concurrent deliveries (serialized by the titled-create lock) pick the same identity. An- existing UNtitled session is the same creation interrupted before its title: it is reused."""+ must never resurrect it), renamed (titled, but not "Bot Chat" — or the lookup had found it) or+ handed off to a messaging lane, and a replacement takes the next one. Derived from durable rows+ only, so a restart and two concurrent deliveries (serialized by the titled-create lock) pick the+ same identity. An existing UNtitled local session is the same creation interrupted before its+ title: it is reused."""from gateway.session_local_recovery import local_identity+ from gateway.session_route_recovery import _messaging_platformfrom hermes_state_mutation_retirement import first_generationbase = 'bot-chat:' + authority.profile_idrequest_id = lambda generation: base if generation == 0 else f'{base}:{generation}'- def titled(conn, sid):- row = conn.execute('SELECT title FROM sessions WHERE id=?', (sid,)).fetchone()- return row is not None and bool(row[0])+ def spent(conn, sid):+ row = conn.execute('SELECT title, source FROM sessions WHERE id=?', (sid,)).fetchone()+ # Handed off (``/handoff``), it is a messaging lane's conversation: its receipt went with it,+ # and a reset's head carried its name there (``hermes_state_local.hand_off_conversations``).+ return row is not None and (bool(row[0]) or _messaging_platform(row[1]) is not None)generation, _sid = first_generation(- authority.db, lambda n: local_identity(authority.profile_id, actor.subject, request_id(n)), spent=titled)+ authority.db, lambda n: local_identity(authority.profile_id, actor.subject, request_id(n)), spent=spent)return request_id(generation)diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex 2a9188cc88a..a6590ff1dd9 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -403,8 +403,7 @@ def release_handed_off_receipts(db, *, epoch):_epoch(conn, epoch)moved = {owner: (target, source) for owner, (target, source) in moved_receipts(conn).items()if _messaging_platform(source) is not None}- hand_off_conversations(conn, moved)- return moved+ return hand_off_conversations(conn, moved)for owner, (target, source) in db._execute_write(write).items():logging.getLogger(__name__).info('Local session %s was handed off to %s (row %s); released its local receipt', owner, source, target)diff --git a/hermes_state_local.py b/hermes_state_local.pyindex 39f9485de21..dfb6541d93c 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -213,17 +213,22 @@ def hand_off_conversations(conn, moved):"""Retire the receipts in *moved* (``moved_receipts``: a messaging lane took over each one'scurrent target) and move the rest of each conversation onto that lane with it. Its earlier``/new`` segments take the lane's identity, so they open there as read-only history (a lane- moved past them) instead of staying local rows no receipt restores; the conversation's title- follows its head, which the lane continues as its own conversation."""- for owner, (target, _source) in moved.items():+ moved past them) instead of staying local rows no receipt restores; the conversation's name+ follows its head, which the lane continues as its own conversation. Returns the receipts it+ handed off: one whose lineage is malformed stays as it is (its own reads refuse it, logged)."""+ handed = {}+ for owner, (target, source) in moved.items():saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + owner,)).fetchone()- lineage = (_receipt(saved[0]) or {}).get('lineage') if saved else None- segments = [sid for sid in dict.fromkeys([owner, *(lineage if isinstance(lineage, list) else ())])- if isinstance(sid, str)]+ lineage = (_receipt(saved[0]) or {}).get('lineage', [owner]) if saved else [owner]+ if not isinstance(lineage, list) or not all(isinstance(sid, str) for sid in lineage):+ continue+ segments = list(dict.fromkeys([owner, *lineage]))conn.execute(f'UPDATE sessions SET ({_LANE_IDENTITY}) = (SELECT {_LANE_IDENTITY} FROM sessions WHERE id=?) ''WHERE id IN (SELECT value FROM json_each(?)) AND id != ?', (target, json.dumps(segments), target))_title_follows_head(conn, owner, _segment_root(conn, segments, target))- release_receipts(conn, moved)+ handed[owner] = (target, source)+ release_receipts(conn, handed)+ return handeddef _receipt(raw):@@ -245,17 +250,16 @@ def _segment_root(conn, segments, target):return segments[index]-_TITLE_RANK = {'derived': 0, 'llm': 1, 'user': 2}--def _title_follows_head(conn, owner, head):- """The conversation's name (a Bot Chat's registry title included) moves to its head, over a title- the segment only got generated; a name the user gave the segment itself stays."""+ """The conversation's name (a Bot Chat's registry title included) moves to its head, over a+ title of lower provenance there (a generated one); a name of equal rank the head carries stays+ (``SessionDB._title_rank``: a pre-provenance title ranks as the user's)."""+ from hermes_state import SessionDBrow = conn.execute('SELECT title, title_source, hidden FROM sessions WHERE id=?', (owner,)).fetchone()if head == owner or row is None or not row[0]:returnkept = conn.execute('SELECT title, title_source FROM sessions WHERE id=?', (head,)).fetchone()- if kept is None or (kept[0] and _TITLE_RANK.get(kept[1], 0) >= _TITLE_RANK.get(row[1], 0)):+ if kept is None or (kept[0] and SessionDB._title_rank(kept[1]) >= SessionDB._title_rank(row[1])):returnconn.execute('UPDATE sessions SET title=NULL WHERE id IN (?,?)', (owner, head))conn.execute('UPDATE sessions SET title=?, title_source=?, hidden=? WHERE id=?', (*row, head))diff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.pyindex 1401a7081c0..8cd93401e61 100644--- a/tests/gateway/test_handoff_local_receipt.py+++ b/tests/gateway/test_handoff_local_receipt.py@@ -270,11 +270,66 @@ async def test_a_second_chat_handed_off_to_the_same_home_chat_supersedes_the_firassert warm.agent(ref) is Noneassert await _bot_row(warm, owner) is None+ # H handed off there again: the lane names H once more, and Y is the one that is history now.+ await _handoff(runner, warm, ref.session_id, telegram)+ warm.authorize(owner, ref, 'session:submit')+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ warm.authorize(owner, other, 'session:submit')+cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')- cold.authorize(owner, other, 'session:control')- cold.authorize(owner, ref, 'session:read')+ cold.authorize(owner, ref, 'session:control')+ cold.authorize(owner, other, 'session:read')with pytest.raises(RuntimeStoreError, match='session_superseded'):- cold.authorize(owner, ref, 'session:control')+ cold.authorize(owner, other, 'session:control')+++async def test_the_bots_own_bot_chat_after_a_reset_handoff_and_the_lanes_new_is_replaced(tmp_path):+ """The Bot Chat a delivery minted (its automatic creation id), reset locally, handed off, then the+ platform's ``/new``: the next delivery mints the next generation. The handed-off creation row+ (its name went to the head) is spent, never reused as an unfinished creation."""+ from gateway.session_authority import initialize_session_authority+ from gateway.session_bot import _target+ from gateway.session_contract import Principal+ runner = _Runner(tmp_path)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ runner._cached_agent_for = lambda route: None+ warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')+ owner = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control',+ 'session:submit'}), 'socket')+ first = (await _target(warm, owner))[0]+ runner.session_store.reset_session(warm.sessions[first.session_id].route)+ telegram = _source()+ route = await _handoff(runner, warm, first.session_id, telegram)+ head = runner.session_store.lookup_by_session_key(route).session_id+ assert warm.db.get_session_by_title('Bot Chat')['id'] == head+ runner.session_store.reset_session(route) # Telegram's /new+ fresh = (await _target(warm, owner))[0].session_id+ assert fresh not in (first.session_id, head)+ assert warm.db.get_session_by_title('Bot Chat')['id'] == fresh+++async def test_a_moved_receipt_with_a_malformed_lineage_never_stops_the_boot(tmp_path, monkeypatch):+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from hermes_state_local import POLICY_PREFIX+ runner = _Runner(tmp_path)+ warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')+ owner = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control'}), 'socket')+ ref = create_local_session(warm, owner, {'request_id': 'chat', 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'frozen', 'toolsets': []})+ with monkeypatch.context() as patch:+ _as_an_older_build(patch)+ await _handoff(runner, warm, ref.session_id, _source())+ key = POLICY_PREFIX + ref.session_id+ warm.db._execute_write(lambda conn: conn.execute(+ "UPDATE state_meta SET value=json_set(value, '$.lineage', json(?)) WHERE key=?",+ (json.dumps([ref.session_id, {}]), key)))+ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')+ with cold.db._read_ctx() as conn:+ assert conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone()def _serve(tmp_path, monkeypatch):