The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a Bot Chat a native ticket can adopt; move a stale-route foreign stamp aside
kshitijk4poore5a86d08d3d8
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex f92dc484f70..4d246d660fa 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -218,7 +218,8 @@ def displaceable_bot_chat(authority, row):unbound CLI/TUI/Desktop row no native open can adopt), else None. Such a row can never beadopted (``validate_legacy_row``), renamed (the canonical title is its identity) or renamedover the API, so it would refuse every delivery for good. A bound local chat, old local history- a native open adopts and a Desktop row a login stamped as its own are never moved."""+ a native open adopts (``_kept_local_history``) and a Desktop row a login stamped as its own are+ never moved."""from hermes_state_local import POLICY_PREFIXfrom hermes_state_local_migration import LEGACY_PREFIX@@ -275,20 +276,26 @@ def release_superseded_bot_chat_at_boot(db, store):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)."""+ or Desktop row a native open adopts (unstamped, or stamped with a subject a native ticket+ carries: the host's own OS identity, or a structured login subject a same-user peer forwards),+ or a Desktop row a served login stamped with its label (kept as on main, even with a route+ column or another profile's name). Any other local-source row no open can ever adopt (a route+ column left by a crash or reconnect, another profile's stamp, or outside Desktop any other+ stamp, such as a login label ``basic:alice``) is not: it held the title and refused every+ delivery for good (#141243, #143715)."""+ from gateway.session_identity import parse_authenticated_subject+ from gateway.session_worker_reservation import owner_worker_subjectfrom hermes_state_local_migration import LEGACY_LOCAL_SOURCES, legacy_account_label, validate_legacy_rowif row.get('source') not in LEGACY_LOCAL_SOURCES:return False- if row.get('user_id') and not legacy_account_label(row):- # A Desktop row a served login stamped is that login's own chat, adopted in place (#140183).- # A stamp on any other local source names no owner this door can reach — it is a submit-only- # principal, a foreign stamp is refused, and a bound row is refused by its route — so a row- # with no binding at all is unadoptable for everyone and held the title for good (#143715).- return row.get('source') == 'desktop' or bool(row.get('chat_id') or row.get('session_key'))+ user_id = row.get('user_id')+ if (user_id and not legacy_account_label(row) and user_id != owner_worker_subject()+ and parse_authenticated_subject(user_id) is None):+ # A Desktop row a login stamped stays where it is, as on main (#140183). On any other local+ # source such a stamp names no subject a native ticket carries, so nobody adopts it (#143715).+ return row.get('source') == 'desktop'try:- validate_legacy_row(db, row)+ validate_legacy_row(db, row, subject=user_id)except RuntimeStoreError:return Falsereturn Truediff --git a/tests/gateway/test_bot_chat_unadoptable_local_title.py b/tests/gateway/test_bot_chat_unadoptable_local_title.pyindex 0378d0e479c..8abd21762da 100644--- a/tests/gateway/test_bot_chat_unadoptable_local_title.py+++ b/tests/gateway/test_bot_chat_unadoptable_local_title.py@@ -1,9 +1,10 @@"""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).+refuse every Bot Chat delivery for good (#141243, #143715).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+local binding; another profile or (outside Desktop) another login may have stamped it.+``adopt_legacy_session`` refuses such a row for every caller, so a cron ``deliver: bot-chat``+failed ``not_found`` on every beat. The door now moves it aside, as itdoes an API or messaging row, and mints the profile's local Bot Chat; adoptable history stays put."""from pathlib import Path@@ -61,51 +62,77 @@ async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lanassert len(db._read_all('SELECT id FROM sessions')) == 2[email protected]('stamp', ['github:alice', 'nous:[email protected]'])[email protected]('source, stamp, route', [+ ('tui', 'github:alice', None),+ ('tui', 'nous:[email protected]', None),+ ('cli', 'basic:alice', None),+ ('tui', 'github:alice', 'agent:main:tui:dm:stale'), # a crash's route column, never bound+ ('tui', 'uid:1001', None), # another OS user, not this host's identity+ ('desktop', 'auth:v1:["basic","","alice"]', 'agent:main:tui:dm:stale'), # a subject, but routed+])@pytest.mark.asyncio-async def test_an_unbound_stamped_bot_chat_is_moved_aside_and_the_delivery_lands(headless, stamp):- # A ``user_id`` on a row with no binding at all names nobody the delivery can reach: the door's- # principal is submit-only (no native transport) and refuses a foreign stamp, so the row held- # the title and refused every delivery for good (#143715). Moving it loses nothing.+async def test_a_bot_chat_another_login_stamped_is_moved_aside_and_the_delivery_lands(+ headless, monkeypatch, source, stamp, route):+ # Outside Desktop, a stamp that is neither this host's identity nor a login subject names no+ # subject a native ticket carries; a crash's route column makes a subject-stamped row (Desktop+ # too) unadoptable. No caller can adopt such a row, so it held the title and refused every+ # delivery for good (#143715). Moving it keeps its id, stamp and messages.from tests.waiting import async_wait_until+ import gateway.session_worker_reservation as reservation+ monkeypatch.setattr(reservation, 'owner_worker_subject', lambda: 'uid:1000') # the fixture's native subjectdb = headless.authority.db- old = _squatter(db, '20260924_173840_909979', column='user_id', value=stamp)+ old = _squatter(db, '20260924_173840_909979', column='user_id', value=stamp, source=source)+ if route:+ db._execute_write(lambda conn: conn.execute('UPDATE sessions SET session_key=? WHERE id=?', (route, old)))db.append_message(old, 'user', 'earlier')first = await _deliver(headless.authority, 'd')new = first['session_id']assert new != old and str(db.get_session(new)['chat_id']).startswith('local-'), firstassert db.get_session_by_title('Bot Chat')['id'] == new- assert db.get_session(old)['title'] == f'Bot Chat (tui {old})' and db.get_session(old)['user_id'] == stamp+ moved = db.get_session(old)+ assert (moved['title'], moved['user_id'], moved['message_count']) == (f'Bot Chat ({source} {old})', stamp, 1)second = await _deliver(headless.authority, 'e')assert second['session_id'] == newawait 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]('source, bound', [- ('tui', True), # a binding names a route the row answers on- ('desktop', False), # a served login's own Desktop row (#140183)-])@pytest.mark.asyncio-async def test_a_stamped_bot_chat_that_names_its_owner_is_never_moved_aside(headless, source, bound):+async def test_a_desktop_bot_chat_a_login_stamped_is_never_moved_aside(headless):+ # A served login's own Desktop row stays that login's (#140183): refused, never renamed.db = headless.authority.db- old = _squatter(db, 'tui_bot_chat', column='user_id', value='github:alice', source=source)- if bound:- db._execute_write(lambda conn: conn.execute(- "UPDATE sessions SET session_key='agent:main:tui:dm:bound' WHERE id=?", (old,)))+ old = _squatter(db, 'desktop_bot_chat', column='user_id', value='github:alice', source='desktop')db.append_message(old, 'user', 'earlier')- with pytest.raises(RuntimeStoreError):+ with pytest.raises(RuntimeStoreError) as refused:await _deliver(headless.authority, 'f')- assert db.get_session_by_title('Bot Chat')['id'] == old, 'an owned row keeps its title'- assert len(db._read_all('SELECT id FROM sessions')) == 1+ assert refused.value.reason == 'not_found'+ assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1[email protected]('stamp', [None, 'uid:1000'])@pytest.mark.asyncio-async def test_kept_local_bot_chat_history_is_never_moved_aside(headless):- # A plain pre-upgrade TUI Bot Chat is adopted in place, never renamed.+async def test_kept_local_bot_chat_history_is_adopted_in_place(headless, monkeypatch, stamp):+ # A plain pre-upgrade TUI Bot Chat, or one stamped with the host's own OS identity (the subject+ # a same-user native ticket carries, ``owner_worker_subject``), is adopted in place with its+ # history: the bot's forever-chat keeps its context instead of restarting empty.+ import gateway.session_worker_reservation as reservation+ monkeypatch.setattr(reservation, 'owner_worker_subject', lambda: 'uid:1000') # the fixture's native subjectdb = headless.authority.db- old = _squatter(db, 'tui_bot_chat', column=None, value=None)+ old = _squatter(db, 'tui_bot_chat', column='user_id' if stamp else None, value=stamp)db.append_message(old, 'user', 'earlier')record = await _deliver(headless.authority, 'c')- assert record['session_id'] == old+ assert record['session_id'] == old and db.get_session(old)['chat_id'] == old+ assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1+++async def test_a_bot_chat_stamped_with_a_forwarded_login_subject_is_never_moved_aside(headless):+ # A same-user peer may mint a native ticket for a structured login subject (#138915), and that+ # ticket adopts its own row, so the row stays where it is, as on main.+ db = headless.authority.db+ old = _squatter(db, 'tui_bot_chat', column='user_id', value='auth:v1:["basic","","alice"]')+ with pytest.raises(RuntimeStoreError) as refused:+ await _deliver(headless.authority, 'f')+ assert refused.value.reason == 'not_found'assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1