The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: migrate queued Bot mailbox identities without replaying claims
Tekniumaf49e2fc0595
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex d95179b8161..3b860e2d1a5 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -65,6 +65,28 @@ async def _record_reply(authority, home, key, future):_write(path, record)+async def _migrate(authority, actor, home, root):+ records = [(path, _read(path)) for path in root.glob('*.json')]+ legacy = [(path, record) for path, record in records+ if record and 'owner' in record and not record.get('admission_id')+ and record['status'] in {'queued', 'claimed'}]+ if not legacy:+ return+ ref, live, entry = _target(authority, actor)+ for path, record in sorted(legacy, key=lambda item: (item[1].get('sequence', item[1]['created_at']), item[0].name)):+ owner = record['owner']+ if owner['profile_home'] != str(home):+ continue+ if record['status'] == 'claimed':+ record.update(status='ambiguous', reason='unknown_execution')+ _write(path, record)+ continue+ if authority.db.get_compression_tip(owner['session_id']) != entry.session_id:+ continue+ await _admit(authority, actor, home, root, _delivery_id(record['delivery_id']),+ record['message'], ref, live, entry, legacy=record)++async def deliver(connection, params):authority, actor = connection.authority, connection.actorhome = _home(authority, actor, params.get('profile'))@@ -79,6 +101,7 @@ async def deliver(connection, params):raise RuntimeStoreError('invalid_params')authority._require_admission_open()with _locked(home) as root:+ await _migrate(authority, actor, home, root)path = root / f'{key}.json'record = _read(path)if record is not None and record.get('admission_id'):@@ -91,24 +114,29 @@ async def deliver(connection, params):ref, live, entry = _target(authority, actor)if params.get('session_id', entry.session_id) != entry.session_id:raise RuntimeStoreError('admission_conflict')- event = MessageEvent(text=message, source=live.source, internal=True,- message_id='bot:' + key, metadata={'gateway_session_key': live.route,- 'gateway_session_id': entry.session_id})- # Pin the physical target before committing. A process death in this- # two-store window leaves an explicit unknown record, never a new target.- record = dict(delivery_id=key, profile_home=str(home), session_id=ref.session_id,- principal_id=actor.subject, message=message, status='ambiguous')- _write(path, record)- receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)- record.update(status='canonical', admission_id=receipt.admission_id)- _write(path, record)- if receipt.status in {'queued', 'started'}:- future = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())- task = asyncio.create_task(_record_reply(authority, home, key, future))- # Keep receipt publication independent of the requesting WebSocket.- tasks = getattr(authority, '_bot_receipt_tasks', None)- if tasks is None:- tasks = authority._bot_receipt_tasks = set()- tasks.add(task)- task.add_done_callback(tasks.discard)- return _result(authority, record)+ return await _admit(authority, actor, home, root, key, message, ref, live, entry)+++async def _admit(authority, actor, home, root, key, message, ref, live, entry, legacy=None):+ path = root / f'{key}.json'+ event = MessageEvent(text=message, source=live.source, internal=True,+ message_id='bot:' + key, metadata={'gateway_session_key': live.route,+ 'gateway_session_id': entry.session_id})+ # Pin the physical target before committing. A process death in this+ # two-store window leaves an explicit unknown record, never a new target.+ record = dict(legacy or {}, delivery_id=key, profile_home=str(home), session_id=ref.session_id,+ principal_id=actor.subject, message=message, status='ambiguous')+ _write(path, record)+ receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)+ record.update(status='canonical', admission_id=receipt.admission_id)+ _write(path, record)+ if receipt.status in {'queued', 'started'}:+ future = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())+ task = asyncio.create_task(_record_reply(authority, home, key, future))+ # Keep receipt publication independent of the requesting WebSocket.+ tasks = getattr(authority, '_bot_receipt_tasks', None)+ if tasks is None:+ tasks = authority._bot_receipt_tasks = set()+ tasks.add(task)+ task.add_done_callback(tasks.discard)+ return _result(authority, record)\ No newline at end of filediff --git a/tests/gateway/fixtures/bot_authority_peer.py b/tests/gateway/fixtures/bot_authority_peer.pyindex 940e8502ada..64bf91f0360 100644--- a/tests/gateway/fixtures/bot_authority_peer.py+++ b/tests/gateway/fixtures/bot_authority_peer.py@@ -50,12 +50,23 @@ def probe(base):await rpc(ws, 'prompt.submit', session_id=sid, input_id='hold', text='HOLD_AUTOMATION')assert await asyncio.to_thread(model.blocked.wait, 20)from tools.bot_mode_dm import _admit_live_dm+ from tools.bot_live_delivery import _locked, _write, _read+ legacy_owner = dict(profile_home=str(home), session_id=sid, lease_id='departed', live_session_id='old-ui')+ with _locked(home) as mailbox:+ for key, status, text in [('b' * 32, 'queued', 'LEGACY_QUEUED_ONCE'),+ ('c' * 32, 'claimed', 'LEGACY_CLAIMED_NEVER')]:+ _write(mailbox / f'{key}.json', dict(delivery_id=key, id=key, owner=legacy_owner,+ **legacy_owner, message=text, status=status, created_at=1, sequence=1))dm = home / 'local-dm.txt'dm.write_text('[Message from @local-sender] LOCAL_DM_ONCE')local = await asyncio.to_thread(_admit_live_dm, home, str(dm))assert local is not None and local['status'] == 'queued', localsame = await asyncio.to_thread(_admit_live_dm, home, str(dm))assert same['admission_id'] == local['admission_id'], same+ with _locked(home) as mailbox:+ migrated = _read(mailbox / ('b' * 32 + '.json'))+ unknown = _read(mailbox / ('c' * 32 + '.json'))+ assert migrated.get('admission_id') and unknown['status'] == 'ambiguous', (migrated, unknown)params = {'id': 'a' * 32, 'profile': 'default', 'message': '[Message from @sender] BOT_DM_ONCE'}wrong = await rpc(ws, 'bot_relay.deliver', **{**params, 'profile': 'wrong-profile'})assert wrong['error']['message'] == 'profile_mismatch', wrong@@ -79,6 +90,9 @@ def probe(base):texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')for r in model.requests if r.get('messages')]assert sum('BOT_DM_ONCE' in str(t) for t in texts) == 1, texts+ assert sum('LOCAL_DM_ONCE' in str(t) for t in texts) == 1, texts+ assert sum('LEGACY_QUEUED_ONCE' in str(t) for t in texts) == 1, texts+ assert not any('LEGACY_CLAIMED_NEVER' in str(t) for t in texts), textsprint(json.dumps({'ledger': rows(), 'inputs': texts, 'lost_ack': True, 'same_target': sid}))try: