The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): judge Bot Chat history by the delivering principal
kshitijk4poor075618f4a2a7
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 7ddf1b4643b..1ac2c3ae982 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -184,7 +184,7 @@ def _home(authority, actor, profile):async def _target(authority, actor):ref = lane = Nonerow = authority.db.get_session_by_title('Bot Chat')- if row is None or (displaced := displaceable_bot_chat(authority, row)) is not None:+ if row is None or (displaced := displaceable_bot_chat(authority, row, actor.subject)) is not None:# None: a concurrent delivery created it first. A title held by an API conversation no FIFO# can own is moved aside first, under the same lock (MSG-21, #140769).ref = await _create_bot_chat(authority, actor, displace=None if row is None else displaced)@@ -212,14 +212,12 @@ async def _target(authority, actor):return ref, live, entry-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, 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 (``_kept_local_history``) and a Desktop row a login stamped as its own are- never moved."""+def displaceable_bot_chat(authority, row, subject=None):+ """The id holding the canonical title when the Bot Chat is a conversation this delivery can+ never adopt, rename (the title is its identity) or rename over the API, so it would refuse+ every delivery for good: an ``api_`` row an older gateway or a plain ``POST /api/sessions``+ minted, a messaging row, or unbound local history ``_kept_local_history`` does not keep for+ the delivering *subject*. Else None: a bound local chat and kept history are never moved."""from hermes_state_local import POLICY_PREFIXfrom hermes_state_local_migration import LEGACY_PREFIX@@ -241,7 +239,7 @@ 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):+ if _kept_local_history(db, candidate, subject):return Nonereturn row['id']@@ -274,31 +272,37 @@ def release_superseded_bot_chat_at_boot(db, store):release_superseded_bot_chat(db, store, tip.get('session_key'), row['id'])-def _kept_local_history(db, row):+def _kept_local_history(db, row, subject=None):"""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 (unstamped, or stamped with the host owner's OS identity,- an owner login label, or a structured login subject),- 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 a foreign- stamp) is not: it held the title and refused every delivery for good (#141243, #143715)."""+ or Desktop row the delivering *subject* or the host owner adopts by the native open's own rule+ (``validate_legacy_row``: unstamped, or stamped with one of that adopter's identities), or a+ Desktop row a foreign login stamped with its label (#140183: kept even with a route column or+ another profile's name). Any other local-source row (a route column left by a crash or+ reconnect, another profile's stamp, a stamp neither adopter owns, or outside Desktop a foreign+ label) is not: kept, it held the title and refused every delivery for good (#141243, #143715).+ *subject* None: the row's own ``auth:v1`` or owner-label stamp is the adopter, as a peer DM's+ turn enters the chat."""+ from gateway.owner_identity import host_owner_subject, same_ownerfrom gateway.session_identity import parse_authenticated_subject- from gateway.owner_identity import same_owner- 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 Falseuser_id = row.get('user_id')- if (user_id and not legacy_account_label(row) and not same_owner(user_id, owner_worker_subject())+ owner = host_owner_subject()+ if (user_id and not legacy_account_label(row) and not same_owner(user_id, owner)+ and not (subject and same_owner(user_id, subject))and parse_authenticated_subject(user_id) is None):- # Keep the Desktop foreign-login exception (#140183). Owner login labels must instead- # reach validation: delivery and native open must agree before this door displaces history.+ # A label neither adopter owns: Desktop keeps it (#140183); elsewhere no open adopts it.return row.get('source') == 'desktop'- try:- validate_legacy_row(db, row, subject=user_id)- except RuntimeStoreError:- return False- return True+ # A forwarded login (control socket) adopts its own stamp; the owner's history is never moved+ # aside for a delivery that cannot adopt it.+ for adopter in dict.fromkeys((user_id if subject is None else subject, owner)):+ try:+ validate_legacy_row(db, row, subject=adopter)+ except RuntimeStoreError:+ continue+ return True+ return Falsedef _moved_aside_by_this_door(authority, holder, pinned):@@ -350,7 +354,7 @@ async def _create_bot_chat(authority, actor, *, displace=None):async with lock:held = authority.db.get_session_by_title('Bot Chat')if held is not None:- if displace is None or held['id'] != displace or displaceable_bot_chat(authority, held) != displace:+ if displace is None or held['id'] != displace or displaceable_bot_chat(authority, held, actor.subject) != displace:return Nonelogger.warning("Bot Chat title held by %s, a conversation no FIFO can own: moving it aside", displace)# False: the title moved since the check. A lane's ``/new`` frees a handed-off Bot Chat'sdiff --git a/tests/gateway/test_bot_chat_owner_adoption.py b/tests/gateway/test_bot_chat_owner_adoption.pyindex 4062b1ced4f..bd67613ac43 100644--- a/tests/gateway/test_bot_chat_owner_adoption.py+++ b/tests/gateway/test_bot_chat_owner_adoption.py@@ -1,4 +1,6 @@-"""Owner login history survives either delivery-first or open-first Bot Chat adoption."""+"""Owner login history survives either delivery-first or open-first Bot Chat adoption, a live+legacy writer refuses the delivery without losing the chat, and a forwarded login delivers into+its own chat but never moves the owner's aside."""import pytest@@ -9,20 +11,26 @@ from tests.waiting import async_wait_untilheadless = peer.headless[email protected]("open_first", [False, True])[email protected]("open_first", [False, True], ids=["delivery-first", "open-first"])@pytest.mark.parametrize(- "stamp", ["basic:alice", "self-hosted:alice", 'auth:v1:["basic","","alice"]']+ "source, stamp",+ [+ ("tui", "basic:alice"),+ ("tui", "self-hosted:alice"),+ ("tui", 'auth:v1:["basic","","alice"]'),+ ("cli", "basic:alice"), # CLI rows follow the TUI rule; one case pins it+ ],)@pytest.mark.asyncioasync def test_owner_chat_retains_identity_history_and_replies_in_both_orders(- headless, monkeypatch, stamp, open_first+ headless, monkeypatch, source, stamp, open_first):import gateway.session_worker_reservation as reservationmonkeypatch.setattr(reservation, "owner_worker_subject", lambda: "uid:1000")db = headless.authority.dbsid = "existing-bot-chat"- db.create_session(sid, source="tui", user_id=stamp)+ db.create_session(sid, source=source, user_id=stamp)db.set_session_title(sid, "Bot Chat")db.append_message(sid, "user", "existing project context")db.append_message(sid, "assistant", "existing answer")@@ -96,3 +104,60 @@ async def test_owner_login_chat_is_not_replaced_while_its_legacy_writer_is_live(assert (db.get_messages_as_conversation(sid)[0]["content"] == "existing project context")+++# A login a same-user peer forwards over the control socket (#138915); no registered provider+# names it, so it keeps its own subject (``principal_subject``) and owns its own stamps.+FORWARDED = 'auth:v1:["github","","alice"]'++[email protected]("open_first", [False, True], ids=["delivery-first", "open-first"])[email protected]("stamp", [FORWARDED, "github:alice"], ids=["subject", "label"])+async def test_a_forwarded_login_delivers_into_its_own_chat_in_both_orders(+ headless, monkeypatch, stamp, open_first+):+ # The forwarded login adopts the chat it stamped, so its delivery must not move that chat+ # aside, whether or not it opened it first.+ import gateway.session_worker_reservation as reservation++ monkeypatch.setattr(reservation, "owner_worker_subject", lambda: "uid:1000")+ db = headless.authority.db+ sid = "forwarded-bot-chat"+ db.create_session(sid, source="tui", user_id=stamp)+ db.set_session_title(sid, "Bot Chat")+ db.append_message(sid, "user", "existing project context")+ login = peer._local_owner(headless.authority, FORWARDED)+ try:+ if open_first:+ await peer._rpc(login, "session.resume", session_id=sid)+ record = await _deliver(headless.authority, "4", connection=login)+ assert record["session_id"] == sid+ assert db.get_session_by_title("Bot Chat")["id"] == sid+ assert [row[0] for row in db._read_all("SELECT id FROM sessions")] == [sid]+ finally:+ await login.close()+++async def test_a_forwarded_login_never_moves_the_owners_chat_aside(headless, monkeypatch):+ # The owner's own Bot Chat stays where it is when a forwarded login that cannot adopt it+ # delivers: that delivery is refused, the owner's history keeps the title.+ import gateway.session_worker_reservation as reservation+ from hermes_state_runtime import RuntimeStoreError++ monkeypatch.setattr(reservation, "owner_worker_subject", lambda: "uid:1000")+ db = headless.authority.db+ sid = "owner-bot-chat"+ db.create_session(sid, source="tui", user_id="basic:alice")+ db.set_session_title(sid, "Bot Chat")+ db.append_message(sid, "user", "existing project context")+ login = peer._local_owner(headless.authority, FORWARDED)+ try:+ with pytest.raises(RuntimeStoreError) as refused:+ await _deliver(headless.authority, "5", connection=login)+ assert refused.value.reason == "not_found"+ assert db.get_session_by_title("Bot Chat")["id"] == sid+ assert [row[0] for row in db._read_all("SELECT id FROM sessions")] == [sid]+ finally:+ await login.close()diff --git a/tests/gateway/test_bot_chat_unadoptable_local_title.py b/tests/gateway/test_bot_chat_unadoptable_local_title.pyindex 41a5a55486c..5ad18bff561 100644--- a/tests/gateway/test_bot_chat_unadoptable_local_title.py+++ b/tests/gateway/test_bot_chat_unadoptable_local_title.py@@ -28,7 +28,7 @@ def _squatter(db, sid, *, column, value, source='tui'):return sid-async def _deliver(authority, key):+async def _deliver(authority, key, connection=None):from gateway.session_authorities import served_profile_namefrom gateway.session_bot import deliverfrom tools.bot_live_delivery import _bot_chat_tip@@ -36,7 +36,7 @@ async def _deliver(authority, key):# 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),+ return await deliver(connection or _local_owner(authority), dict(id=key * 32, profile=served_profile_name(home),message='cron beat', **({'session_id': pinned} if pinned else {})))@@ -69,14 +69,19 @@ async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lan('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+ ('desktop', 'basic:alice', 'agent:main:tui:dm:stale'), # an owner label is no foreign login: routed, moved+ ('tui', 'auth:v1:["local","","uid:1001"]', None), # another OS user's subject+ ('tui', 'auth:v1:["github","","alice"]', None), # a subject no registered login names+ ('desktop', 'auth:v1:["local","","uid:1001"]', None), # a subject is no Desktop login label])@pytest.mark.asyncio-async def test_a_bot_chat_another_login_stamped_is_moved_aside_and_the_delivery_lands(+async def test_an_unadoptable_stamped_bot_chat_is_moved_aside_and_the_delivery_lands(headless, monkeypatch, source, stamp, route):- # Foreign stamps and stale routes remain unadoptable. An owner's login label alone no longer- # makes a row foreign, but a crash's route column still prevents adoption (Desktop too).+ # Foreign stamps (a label outside Desktop, any ``auth:v1`` subject the owner does not own) and+ # stale routes are unadoptable. An owner's login label alone does not make a row foreign, but a+ # crash's route column still prevents adoption (Desktop too).# No caller can adopt these rows, so they held the title and refused every- # delivery for good (#143715). Moving it keeps its id, stamp and messages.+ # delivery for good (#143715). Moving one keeps its id, stamp and messages.from tests.waiting import async_wait_untilimport gateway.session_worker_reservation as reservationmonkeypatch.setattr(reservation, 'owner_worker_subject', lambda: 'uid:1000') # the fixture's native subjectdiff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.pyindex 297d17f8318..95abfa68eae 100644--- a/tests/gateway/test_handoff_local_receipt.py+++ b/tests/gateway/test_handoff_local_receipt.py@@ -316,8 +316,8 @@ async def test_a_delivery_racing_the_lanes_new_mints_the_fresh_bot_chat(tmp_pathrunner.session_store.reset_session(route)seen = []- def racing(authority, row):- found = displaceable(authority, row)+ def racing(authority, row, subject=None):+ found = displaceable(authority, row, subject)seen.append(found)if lands == 'after the title read' and len(seen) == 1:runner.session_store.reset_session(route) # the lane held it when the delivery read itdiff --git a/tests/gateway/test_peer_dm_bot_chat_headless.py b/tests/gateway/test_peer_dm_bot_chat_headless.pyindex 1db39ad44f6..29d7caf4bef 100644--- a/tests/gateway/test_peer_dm_bot_chat_headless.py+++ b/tests/gateway/test_peer_dm_bot_chat_headless.py@@ -246,13 +246,14 @@ async def _peer_minted(headless):return session_id-def _local_owner(authority):+def _local_owner(authority, user_id='uid:1000'):"""The Desktop/CLI's own connection: an interactive ticket redeemed on the loopback socket- (``gateway/run_api.py``), the identity ``hermes chat``, the Desktop and ``bot_relay.deliver`` use."""+ (``gateway/run_api.py``), the identity ``hermes chat``, the Desktop and ``bot_relay.deliver`` use.+ *user_id*: the login a same-user peer forwards on that ticket (control socket, #138915)."""from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIESfrom gateway.session_controls import AuthorityConnectionreturn AuthorityConnection(authority, object(), {- 'user_id': 'uid:1000', 'provider': 'local', 'profile_id': authority.profile_id,+ 'user_id': user_id, 'provider': 'local', 'profile_id': authority.profile_id,'instance_id': authority.instance_id, 'capabilities': sorted(_PURPOSE_CAPABILITIES['interactive']),'native_bootstrap': True, 'profile_scope': 'profile'}, operator=True)