The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: move an unadoptable local Bot Chat title aside so cron bot-chat delivers
Teknium4cb566e1df15
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex f7022d58741..5c887b80403 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -204,22 +204,20 @@ async def _target(authority, actor):def displaceable_bot_chat(authority, row):"""The id holding the canonical title when the Bot Chat is a conversation no FIFO can own (an- ``api_`` row an older gateway or a plain ``POST /api/sessions`` minted, a messaging row), else- None. Such a row can never be adopted (``validate_legacy_row``), renamed (the canonical title- is its identity) or renamed over the API, so it would refuse every delivery for good. A bound- local chat and old local history (CLI, TUI, Desktop rows a native open adopts) are never moved."""+ ``api_`` row an older gateway or a plain ``POST /api/sessions`` minted, a messaging row, an+ unbound CLI/TUI/Desktop row no native open can adopt), else None. Such a row can never be+ adopted (``validate_legacy_row``), renamed (the canonical title is its identity) or renamed+ over the API, so it would refuse every delivery for good. A bound local chat, old local history+ a native open adopts and a local row a login stamped as its own are never moved."""from hermes_state_local import POLICY_PREFIX- from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, LEGACY_PREFIX+ from hermes_state_local_migration import LEGACY_PREFIX- def owned(candidate):- return (str(candidate.get('chat_id') or '').startswith('local-')- or candidate.get('source') in LEGACY_LOCAL_SOURCES)- if owned(row): # every delivery asks: a bound local chat answers from its own row, with no read- return None+ if str(row.get('chat_id') or '').startswith('local-'):+ return None # every delivery asks: a bound local chat answers from its own row, with no readdb = authority.dbtip = db.get_session(db.get_compression_tip(row['id']) or row['id'])for candidate in (row, tip):- if candidate is None or owned(candidate):+ if candidate is None or str(candidate.get('chat_id') or '').startswith('local-'):return Nonechat_id = str(candidate.get('chat_id') or '')with db._read_ctx() as conn:@@ -227,9 +225,41 @@ def displaceable_bot_chat(authority, row):(POLICY_PREFIX + (chat_id or candidate['id']),LEGACY_PREFIX + (chat_id or candidate['id']))).fetchone():return None+ if _kept_local_history(db, candidate):+ return Nonereturn row['id']+def _kept_local_history(db, row):+ """Whether an unbound row is local history the Bot Chat door must leave in place: a CLI, TUI+ or Desktop row a native open adopts, or one a login stamped as its owner. A local-source row+ no open can ever adopt (a route column left by a crash or reconnect, another profile's stamp)+ is not: it held the title and refused every delivery for good (#141243)."""+ from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, legacy_account_label, validate_legacy_row+ if row.get('source') not in LEGACY_LOCAL_SOURCES:+ return False+ if row.get('user_id') and not legacy_account_label(row):+ return True+ try:+ validate_legacy_row(db, row)+ except RuntimeStoreError:+ return False+ return True+++def _moved_aside_by_this_door(authority, holder, pinned):+ """Whether *pinned*, the Bot Chat the producer discovered, is the title holder this delivery's+ ``_target`` just moved aside. The producer pins the id it read before asking, so the first+ delivery after a move would otherwise be refused ``admission_conflict`` for the chat the door+ itself replaced, and land only on the next beat."""+ if holder is None:+ return False+ db = authority.db+ if pinned not in (holder['id'], db.get_compression_tip(holder['id'])):+ return False+ return str((db.get_session(holder['id']) or {}).get('title') or '').startswith('Bot Chat (')++def _displace_bot_chat(db, sid):"""Free the canonical title from *sid*: it keeps its id and history under a visible name theuser can find, rename or delete: ``Bot Chat (API <id>)`` for an API conversation, else named by@@ -747,8 +777,10 @@ async def _deliver(connection, params):return answerif record is not None:raise RuntimeStoreError('unknown_execution')+ holder = authority.db.get_session_by_title('Bot Chat')ref, live, entry = await _target(authority, actor)- if params.get('session_id', entry.session_id) != entry.session_id:+ pinned = params.get('session_id', entry.session_id)+ if pinned != entry.session_id and not _moved_aside_by_this_door(authority, holder, pinned):raise RuntimeStoreError('admission_conflict')return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,notification_category=category)diff --git a/tests/gateway/test_bot_chat_unadoptable_local_title.py b/tests/gateway/test_bot_chat_unadoptable_local_title.pynew file mode 100644index 00000000000..81884d1a503--- /dev/null+++ b/tests/gateway/test_bot_chat_unadoptable_local_title.py@@ -0,0 +1,78 @@+"""A local row that holds the canonical "Bot Chat" title but no native open can ever adopt does not+refuse every Bot Chat delivery for good (#141243).++A crash or reconnect can leave a CLI/TUI/Desktop row titled "Bot Chat" with a route column but no+local binding (or another profile's stamp). ``adopt_legacy_session`` refuses it for every caller, so+a cron ``deliver: bot-chat`` failed ``not_found`` on every beat. The door now moves it aside, as it+does an API or messaging row, and mints the profile's local Bot Chat; adoptable history stays put.+"""+from pathlib import Path++import pytest++from hermes_state_runtime import RuntimeStoreError++from tests.gateway import test_peer_dm_bot_chat_headless as _headless_gateway++# The headless gateway fixture: one real authority over a SessionDB in a temp HERMES_HOME.+headless = _headless_gateway.headless+_local_owner = _headless_gateway._local_owner+++def _squatter(db, sid, *, column, value):+ db.create_session(sid, 'tui')+ db.set_session_title(sid, 'Bot Chat')+ if column:+ db._execute_write(lambda conn: conn.execute(f'UPDATE sessions SET {column}=? WHERE id=?', (value, sid)))+ return sid+++async def _deliver(authority, key):+ from gateway.session_authorities import served_profile_name+ from gateway.session_bot import deliver+ from tools.bot_live_delivery import _bot_chat_tip+ home = Path(authority.db.db_path).parent.resolve()+ # The cron producer's door: ``bot_relay.deliver`` on a local interactive connection, no author,+ # pinned to the Bot Chat it discovered first (``find_canonical_live_owner``).+ pinned = _bot_chat_tip(home)+ return await deliver(_local_owner(authority), dict(id=key * 32, profile=served_profile_name(home),+ message='cron beat', **({'session_id': pinned} if pinned else {})))++[email protected]('column, value', [+ ('session_key', 'agent:main:tui:dm:stale'), # route left by a crash, never bound+ ('profile_name', 'another-profile'), # stamped by another profile+])+async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lands(headless, column, value):+ from tests.waiting import async_wait_until+ db = headless.authority.db+ old = _squatter(db, '20261018_071332_c8e3e4', column=column, value=value)+ first = await _deliver(headless.authority, 'a') # pinned to the squatter: the beat still lands+ new = first['session_id']+ assert new != old and str(db.get_session(new)['chat_id']).startswith('local-'), first+ assert db.get_session_by_title('Bot Chat')['id'] == new+ assert db.get_session(old)['title'] == f'Bot Chat (tui {old})', 'the old row keeps its id under a visible name'+ # Every later beat finds the minted chat by title: no further move, no second Bot Chat.+ second = await _deliver(headless.authority, 'b')+ assert second['session_id'] == new+ await async_wait_until(lambda: len(headless.executed) == 2, timeout=10, interval=.05)+ assert [sid for sid, _, _ in headless.executed] == [new, new]+ assert len(db._read_all('SELECT id FROM sessions')) == 2++[email protected]('column, value', [(None, None), ('user_id', 'github:alice')])+async def test_kept_local_bot_chat_history_is_never_moved_aside(headless, column, value):+ # A plain pre-upgrade TUI Bot Chat is adopted in place; a row a login stamped as its own stays+ # that login's (refused, never renamed). Neither loses its title.+ db = headless.authority.db+ old = _squatter(db, 'tui_bot_chat', column=column, value=value)+ db.append_message(old, 'user', 'earlier')+ try:+ record = await _deliver(headless.authority, 'c')+ except RuntimeStoreError as exc:+ assert column == 'user_id' and exc.reason == 'not_found'+ else:+ assert column is None and record['session_id'] == old+ assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1