Skip to content

The agent that grows with you

fix: adopt legacy local history through trusted session owner

Tekniumcb748e7a193a
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 0dc0fef2d8a..dfaad8e5ad6 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -57,7 +57,12 @@ class SessionAuthority:
row = self.db.get_session(ref.session_id)
if row is None:
raise RuntimeStoreError('not_found')
- if str(row.get('chat_id') or '').startswith('local-'):
+ from hermes_state_local import POLICY_PREFIX
+ with self.db._read_ctx() as conn:
+ from hermes_state_local_migration import LEGACY_PREFIX
+ local = conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)',
+ (POLICY_PREFIX + ref.session_id, LEGACY_PREFIX + ref.session_id)).fetchone()
+ if local or str(row.get('chat_id') or '').startswith('local-'):
from gateway.session_local_recovery import restore_local_session
restore_local_session(self, ref.session_id)
else:
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 82934b02a90..5d632685e51 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -29,10 +29,10 @@ def _target(authority, actor):
raise RuntimeStoreError('not_found')
tip = authority.db.get_compression_tip(row['id'])
target = authority.db.get_session(tip)
- if target is None or not str(target.get('chat_id') or '').startswith('local-'):
- # A legacy transcript needs an owner-side binding migration, not a new agent.
- raise RuntimeStoreError('runtime_coordination_required')
- ref = SessionRef(authority.profile_id, target['chat_id'])
+ if target is None:
+ raise RuntimeStoreError('not_found')
+ from gateway.session_local_migration import resolve_local_target
+ ref = resolve_local_target(authority, actor, target['id'])
authority.authorize(actor, ref, 'session:submit')
live = authority.sessions[ref.session_id]
entry = authority.runner.session_store.lookup_by_session_key(live.route)
@@ -104,12 +104,16 @@ async def _migrate(authority, actor, home, root):
owner = record['owner']
if owner['profile_home'] != str(home):
continue
+ if authority.db.get_compression_tip(owner['session_id']) != entry.session_id:
+ continue
+ from hermes_cli.active_sessions import active_session_liveness_guard
+ with active_session_liveness_guard(owner['session_id'], registry_home=home) as active:
+ if active:
+ raise RuntimeStoreError('runtime_coordination_required')
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)
@@ -130,10 +134,16 @@ async def recover_bot_deliveries(authority):
if row is None:
return
target = authority.db.get_session(authority.db.get_compression_tip(row['id']))
- if target is None or not str(target.get('chat_id') or '').startswith('local-'):
- return # Historical binding migration belongs to the session owner.
+ if target is None:
+ return
+ from hermes_state_local import POLICY_PREFIX
+ with authority.db._read_ctx() as conn:
+ bound = conn.execute('SELECT 1 FROM state_meta WHERE key=?',
+ (POLICY_PREFIX + (target.get('chat_id') or target['id']),)).fetchone()
+ if not bound:
+ return # Unowned history requires a native ticket, never the first remote sender.
actor = Principal(target['user_id'], authority.profile_id,
- frozenset({'session:submit'}), 'bot-owner-recovery')
+ frozenset({'session:submit', 'session:read'}), 'bot-owner-recovery')
await _migrate(authority, actor, home, root)
@@ -161,9 +171,15 @@ 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'):
+ if record['message'] != message or record['principal_id'] != actor.subject:
+ raise RuntimeStoreError('admission_conflict')
+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')
+ return _result(authority, record)
+ await _migrate(authority, actor, home, root)
+ record = _read(path)
if record is not None and record.get('admission_id'):
if record['message'] != message or record['principal_id'] != actor.subject:
raise RuntimeStoreError('admission_conflict')
diff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.py
new file mode 100644
index 00000000000..1fdd768396e
--- /dev/null
+++ b/gateway/session_local_migration.py
@@ -0,0 +1,93 @@
+"""Owner-only adoption of pre-authority local transcripts.
+
+An old transcript has no authenticated subject. Only a redeemed same-profile
+native control ticket may adopt it; remote login is not evidence of ownership.
+The historical ID becomes the stable logical owner without copying its messages.
+Compression and reset may later advance the physical target, never FIFO identity.
+"""
+from dataclasses import asdict, replace
+from datetime import datetime, timezone
+from pathlib import Path
+
+from gateway.config import Platform
+from gateway.session import SessionEntry, SessionSource
+from gateway.session_contract import SessionRef
+from hermes_state_runtime import RuntimeStoreError
+
+
+def bind_native_transport(authority, actor, identity):
+ if (identity.get('provider') == 'local'
+ and identity.get('profile_id') == authority.profile_id
+ and identity.get('instance_id') == authority.instance_id
+ and actor.profile_id == authority.profile_id
+ and 'session:create' in actor.capabilities):
+ if not hasattr(authority, '_native_legacy_transports'):
+ authority._native_legacy_transports = {}
+ authority._native_legacy_transports[actor.transport_id] = actor
+
+
+def unbind_native_transport(authority, actor):
+ getattr(authority, '_native_legacy_transports', {}).pop(actor.transport_id, None)
+
+
+def resolve_local_target(authority, actor, sid):
+ """Resolve physical history IDs without silently adopting canonical corruption."""
+ db = authority.db
+ row = db.get_session(sid)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ from hermes_state_local import POLICY_PREFIX
+ with db._read_ctx() as conn:
+ from hermes_state_local_migration import LEGACY_PREFIX
+ bound = conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)',
+ (POLICY_PREFIX + (row.get('chat_id') or sid), LEGACY_PREFIX + (row.get('chat_id') or sid))).fetchone()
+ if bound or str(row.get('chat_id') or '').startswith('local-'):
+ ref = SessionRef(authority.profile_id, row['chat_id'])
+ authority.authorize(actor, ref, 'session:read')
+ return ref
+ return adopt_legacy_session(authority, actor, row)
+
+
+def adopt_legacy_session(authority, actor, row):
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if (getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) != actor
+ or not {'session:read', 'session:create'} <= actor.capabilities):
+ raise RuntimeStoreError('not_found')
+ from hermes_state_local_migration import validate_legacy_row
+ validate_legacy_row(authority.db, row)
+ authority._require_admission_open()
+ from gateway.run import _load_gateway_config, _resolve_gateway_model
+ from gateway.session_policy import build_policy, bind_launch_key
+ from gateway.session_local_recovery import restore_local_session
+ from hermes_state_local import commit_local_session
+ from hermes_cli.active_sessions import active_session_liveness_guard, ActiveSessionRegistryError
+
+ request_id = 'legacy:' + row['id']
+ sid = row['id']
+ params = {'source': row['source']}
+ if row.get('cwd'):
+ params['cwd'] = row['cwd']
+ if row.get('model'):
+ params['model'] = row['model']
+ private = {}
+ policy = build_policy(params, _load_gateway_config(), private_secrets=private)
+ if policy.model is None:
+ policy = replace(policy, model=_resolve_gateway_model(policy.config()))
+ policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)
+ source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id=actor.subject, chat_type='dm')
+ route = authority.runner.session_store._generate_session_key(source)
+ now = datetime.fromtimestamp(row['started_at'], timezone.utc)
+ entry = SessionEntry(route, row['id'], now, now, origin=source, platform=Platform.LOCAL)
+ receipt = {'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
+ 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy),
+ 'legacy_session_id': row['id'], 'lineage': [row['id']]}
+ try:
+ # Same lock order as old Bot Chat: mailbox (if any), liveness, SQLite.
+ with active_session_liveness_guard(row['id'], registry_home=Path(authority.db.db_path).parent) as active:
+ if active:
+ raise RuntimeStoreError('runtime_coordination_required')
+ commit_local_session(authority.db, epoch=authority.epoch, receipt=receipt)
+ except ActiveSessionRegistryError as exc:
+ raise RuntimeStoreError('runtime_coordination_required') from exc
+ return restore_local_session(authority, sid)
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index c54b3740997..8b507614959 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -23,7 +23,8 @@ def restore_local_session(authority, sid):
try:
if receipt['profile_id'] != authority.profile_id:
raise RuntimeStoreError('profile_mismatch')
- chat_id = local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id'])
+ chat_id = (receipt['legacy_session_id'] if 'legacy_session_id' in receipt else
+ local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id']))
if receipt['session_id'] != sid or sid != chat_id:
raise ValueError('identity mismatch')
source = SessionSource(platform=Platform.LOCAL, chat_id=chat_id,
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.py
index 8fbf07cde23..3a97972f752 100644
--- a/gateway/session_local_title.py
+++ b/gateway/session_local_title.py
@@ -6,7 +6,6 @@ applies the classic CLI rule (``hermes_cli.main._resolve_session_by_name_or_id``
"""
from __future__ import annotations
-from gateway.session_contract import SessionRef
from hermes_state_runtime import RuntimeStoreError
@@ -21,13 +20,13 @@ def resolve_titled_session(authority, actor, name, *, missing_ok=False):
row = db.get_session(name)
sid = row['id'] if row else db.resolve_session_by_title(name)
tip = db.get_session(db.get_compression_tip(sid) or sid) if sid else None
- if tip is None or not str(tip.get('chat_id') or '').startswith('local-'):
+ if tip is None:
if missing_ok:
return None
raise RuntimeStoreError('not_found')
- ref = SessionRef(authority.profile_id, tip['chat_id'])
try:
- authority.authorize(actor, ref, 'session:read')
+ from gateway.session_local_migration import resolve_local_target
+ ref = resolve_local_target(authority, actor, tip['id'])
except RuntimeStoreError as exc:
if exc.reason == 'permission_denied':
raise RuntimeStoreError('not_found') from None
diff --git a/hermes_state_local.py b/hermes_state_local.py
index 99d79505cbc..ee96cefa2c0 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -26,15 +26,20 @@ def commit_local_session(db, *, epoch, receipt):
if not same:
raise RuntimeStoreError('invalid_params')
return saved
- if conn.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone():
+ if ('legacy_session_id' not in receipt and
+ conn.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone()):
raise RuntimeStoreError('storage_unavailable')
if conn.execute("SELECT 1 FROM gateway_routing WHERE scope='' AND session_key=?", (route,)).fetchone():
raise RuntimeStoreError('admission_conflict')
+ if 'legacy_session_id' in receipt:
+ from hermes_state_local_migration import bind_legacy_target
+ bind_legacy_target(db, conn, receipt)
policy, entry = receipt['policy'], receipt['entry']
from datetime import datetime
started = datetime.fromisoformat(entry['created_at']).timestamp()
conn.execute('''INSERT INTO sessions(id,source,user_id,session_key,chat_id,chat_type,
- model,cwd,profile_name,origin_json,started_at) VALUES(?,?,?,?,?,'dm',?,?,?,?,?)''',
+ model,cwd,profile_name,origin_json,started_at) VALUES(?,?,?,?,?,'dm',?,?,?,?,?)
+ ON CONFLICT(id) DO NOTHING''',
(sid, policy['source'], receipt['principal_id'], route, entry['origin']['chat_id'],
policy['model'], policy['cwd'], db._own_profile_name(), _json(entry['origin']), started))
conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?)",
diff --git a/hermes_state_local_lineage.py b/hermes_state_local_lineage.py
index 628c30b7227..9181eced536 100644
--- a/hermes_state_local_lineage.py
+++ b/hermes_state_local_lineage.py
@@ -12,11 +12,14 @@ from hermes_state_runtime import RuntimeStoreError, _epoch, _json
def validate_local_lineage(conn, receipt):
from hermes_state_compression import _CHAIN_STEP_SQL
from gateway.session_local_recovery import local_identity
- if receipt['session_id'] != local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id']):
+ if ('legacy_session_id' not in receipt and
+ receipt['session_id'] != local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id'])):
raise RuntimeStoreError('storage_unavailable')
- lineage = receipt.get('lineage', [receipt['session_id']])
+ from hermes_state_local_migration import legacy_lineage_root
+ root = legacy_lineage_root(conn, receipt)
+ lineage = receipt.get('lineage', [root])
if (not isinstance(lineage, list) or not lineage or len(set(lineage)) != len(lineage)
- or lineage[0] != receipt['session_id'] or lineage[-1] != receipt['entry']['session_id']):
+ or lineage[0] != root or lineage[-1] != receipt['entry']['session_id']):
raise RuntimeStoreError('storage_unavailable')
for parent_id, child_id in zip(lineage, lineage[1:]):
parent = conn.execute('SELECT end_reason FROM sessions WHERE id=?', (parent_id,)).fetchone()
@@ -50,12 +53,16 @@ def local_physical_target(conn, session_id):
def advance_local_target(conn, parent_session_id, child_session_id, *, entry=None):
parent = conn.execute('SELECT * FROM sessions WHERE id=?', (parent_session_id,)).fetchone()
logical_id = parent['chat_id'] if parent else None
- if not logical_id or not logical_id.startswith('local-'):
+ if not logical_id:
return
key = POLICY_PREFIX + logical_id
raw = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
if raw is None:
- raise RuntimeStoreError('storage_unavailable')
+ from hermes_state_local_migration import LEGACY_PREFIX
+ legacy = conn.execute('SELECT 1 FROM state_meta WHERE key=?', (LEGACY_PREFIX + logical_id,)).fetchone()
+ if logical_id.startswith('local-') or legacy:
+ raise RuntimeStoreError('storage_unavailable')
+ return
try:
receipt = json.loads(raw[0])
if (receipt['session_id'] != logical_id or receipt['entry']['session_id'] != parent_session_id
diff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.py
new file mode 100644
index 00000000000..c92bbe25f4a
--- /dev/null
+++ b/hermes_state_local_migration.py
@@ -0,0 +1,60 @@
+"""Transactional legacy binding; never a second transcript writer."""
+import json
+import time
+
+from hermes_state_runtime import RuntimeStoreError, _json
+
+LEGACY_PREFIX = 'gateway.local_legacy.v1:'
+
+
+def validate_legacy_row(db, row):
+ # Unrouted old CLI/TUI/GUI history only. Existing identity, foreign profile,
+ # API, messaging, delegate and canonical rows require their own authority.
+ if (row['source'] not in {'cli', 'tui', 'gui'}
+ or any(row.get(k) for k in ('session_key', 'chat_id', 'user_id', 'origin_json'))
+ or row.get('profile_name') not in (None, '', db._own_profile_name() or 'default')):
+ raise RuntimeStoreError('not_found')
+
+
+def bind_legacy_target(db, conn, receipt):
+ target = receipt['legacy_session_id']
+ if target != receipt['session_id']:
+ raise RuntimeStoreError('storage_unavailable')
+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (target,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ validate_legacy_row(db, dict(row))
+ from hermes_state_mutation_binding import BINDING_PREFIX
+ imported = conn.execute('SELECT value FROM state_meta WHERE key=?', (BINDING_PREFIX + target,)).fetchone()
+ if imported and json.loads(imported[0]) != [receipt['profile_id'], receipt['principal_id']]:
+ raise RuntimeStoreError('permission_denied')
+ from hermes_state_compression import _CHAIN_STEP_SQL
+ if conn.execute(_CHAIN_STEP_SQL, (target,)).fetchone() is not None:
+ raise RuntimeStoreError('admission_conflict')
+ from hermes_state_mutation_guards import require_idle
+ require_idle(db, conn, [target])
+ root = db._session_turn_lease_key_on_conn(conn, target)
+ if conn.execute('SELECT 1 FROM session_turn_leases WHERE conversation_id=? AND expires_at>?',
+ (root, time.time())).fetchone():
+ raise RuntimeStoreError('runtime_coordination_required')
+ key = LEGACY_PREFIX + target
+ if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone():
+ raise RuntimeStoreError('storage_unavailable')
+ source = receipt['entry']['origin']
+ conn.execute('UPDATE sessions SET ended_at=NULL,end_reason=NULL,session_key=?,chat_id=?,user_id=?,chat_type=?,origin_json=? WHERE id=?',
+ (receipt['route'], receipt['session_id'], receipt['principal_id'], 'dm', _json(source), target))
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, _json({
+ 'session_id': receipt['session_id'], 'profile_id': receipt['profile_id'],
+ 'principal_id': receipt['principal_id'], 'legacy_session_id': target})))
+
+
+def legacy_lineage_root(conn, receipt):
+ root = receipt.get('legacy_session_id', receipt['session_id'])
+ if 'legacy_session_id' in receipt:
+ if root != receipt['session_id']:
+ raise RuntimeStoreError('storage_unavailable')
+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (LEGACY_PREFIX + root,)).fetchone()
+ expected = {k: receipt[k] for k in ('session_id', 'profile_id', 'principal_id', 'legacy_session_id')}
+ if row is None or json.loads(row[0]) != expected:
+ raise RuntimeStoreError('storage_unavailable')
+ return root
diff --git a/tests/gateway/fixtures/legacy_bot_mailbox.py b/tests/gateway/fixtures/legacy_bot_mailbox.py
new file mode 100644
index 00000000000..0bc9ad9ab85
--- /dev/null
+++ b/tests/gateway/fixtures/legacy_bot_mailbox.py
@@ -0,0 +1,13 @@
+"""Executed with the pre-authority checkout on PYTHONPATH, not the new writer."""
+import sys
+from pathlib import Path
+from tools.bot_live_delivery import deliver_to_live_owner, claim_pending_delivery
+
+home, sid = Path(sys.argv[1]), sys.argv[2]
+owner = dict(profile_home=str(home), session_id=sid, lease_id='departed-owner', live_session_id='old-native')
+deliver_to_live_owner(home, owner, 'LEGACY_CLAIMED_NEVER', delivery_id='c' * 32)
+assert claim_pending_delivery(home, owner)['delivery_id'] == 'c' * 32
+deliver_to_live_owner(home, owner, 'LEGACY_QUEUED_ONCE', delivery_id='b' * 32)
+foreign = dict(owner, session_id='unrelated-history')
+deliver_to_live_owner(home, foreign, 'UNRELATED_NEVER', delivery_id='d' * 32)
+assert claim_pending_delivery(home, foreign)['delivery_id'] == 'd' * 32
diff --git a/tests/gateway/fixtures/legacy_migration_probe.py b/tests/gateway/fixtures/legacy_migration_probe.py
new file mode 100644
index 00000000000..69bac6d2876
--- /dev/null
+++ b/tests/gateway/fixtures/legacy_migration_probe.py
@@ -0,0 +1,100 @@
+"""Actual classic CLI persistence followed by native owner migration (loopback)."""
+import asyncio
+from http.server import ThreadingHTTPServer
+import json
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+import threading
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+def probe(base, legacy_root, owner_root=None):
+ fixture_root = Path(__file__).resolve().parents[3]
+ root = owner_root or fixture_root
+ home, user = base / 'state', base / 'user'
+ home.mkdir(parents=True); user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({'model': {'provider': 'custom', 'default': 'legacy-model', 'base_url': url},
+ 'gateway': {'multiplex_profiles': False}, 'platform_toolsets': {'cli': []},
+ 'auxiliary': {'title_generation': {'enabled': False}}}))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(legacy_root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)
+ def cli(checkout, *args):
+ result = subprocess.run([sys.executable, '-m', 'hermes_cli.main', 'chat', *args],
+ cwd=checkout, env={**env, 'PYTHONPATH': str(checkout)}, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=120)
+ (home / ('cli-' + str(len(list(home.glob('cli-*')))) + '.log')).write_text(result.stdout + result.stderr)
+ assert result.returncode == 0, result.stdout + result.stderr
+ return result.stdout
+ def query(sql, args=()):
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ db.row_factory = sqlite3.Row
+ return [dict(r) for r in db.execute(sql, args)]
+ async def wait_settled():
+ async with asyncio.timeout(45):
+ while any(r['status'] != 'terminal' for r in query('SELECT status FROM session_admissions')):
+ await asyncio.sleep(.05)
+ async def run(desc):
+ async with websocket(home, desc) as ws:
+ first = await rpc(ws, 'session.resume', session_id=sid)
+ assert first.get('result', {}).get('session_id') == sid, first
+ assert 'OLD_HISTORY' in json.dumps(first['result']['messages']), first
+ params = {'id': 'a' * 32, 'profile': 'default', 'message': 'BOT_NEW_INPUT'}
+ result = await rpc(ws, 'bot_relay.deliver', **params)
+ assert 'result' in result, result
+ await wait_settled()
+ retry = await rpc(ws, 'bot_relay.deliver', **params)
+ assert retry['result']['admission_id'] == result['result']['admission_id'], retry
+ assert retry['result']['status'] == 'settled', retry
+ return first, retry
+ try:
+ cli(legacy_root, '-c', 'Bot Chat', '--create-if-missing', '--toolsets', '', '-q', 'OLD_HISTORY')
+ old = query("SELECT * FROM sessions WHERE title='Bot Chat'")[0]
+ sid = old['id']
+ assert not old['chat_id'] and not old['session_key'], old
+ assert not query("SELECT key FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%'")
+ subprocess.run([sys.executable, str(fixture_root / 'tests/gateway/fixtures/legacy_bot_mailbox.py'), str(home), sid],
+ cwd=legacy_root, env=env, stdin=subprocess.DEVNULL, check=True, timeout=30)
+ env['PYTHONPATH'] = str(root)
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ first, retry = asyncio.run(run(desc))
+ cli(root, '--resume', sid, '-q', 'CLI_NEW_INPUT')
+ async def restarted(desc):
+ async with websocket(home, desc) as ws:
+ result = await rpc(ws, 'session.resume', session_id=sid)
+ assert result.get('result', {}).get('session_id') == sid, result
+ assert 'CLI_NEW_INPUT' in json.dumps(result['result']['messages']), result
+ return result
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ resumed = asyncio.run(restarted(desc))
+ mailbox = home / 'runtime/bot_live_delivery'
+ queued = json.loads((mailbox / ('b' * 32 + '.json')).read_text())
+ claimed = json.loads((mailbox / ('c' * 32 + '.json')).read_text())
+ foreign = json.loads((mailbox / ('d' * 32 + '.json')).read_text())
+ assert queued.get('admission_id') and queued['status'] == 'settled', queued
+ assert claimed['status'] == 'ambiguous' and foreign['status'] == 'claimed'
+ inputs = [str(next((m.get('content') for m in reversed(r['messages']) if m['role'] == 'user'), '')) for r in peer.requests]
+ assert sum('LEGACY_QUEUED_ONCE' in text for text in inputs) == 1, inputs
+ assert not any('LEGACY_CLAIMED_NEVER' in text or 'UNRELATED_NEVER' in text for text in inputs)
+ current = query('SELECT * FROM sessions WHERE id=?', (sid,))[0]
+ assert current['title'] == old['title'] and current['parent_session_id'] == old['parent_session_id']
+ new = [r for r in peer.requests if 'BOT_NEW_INPUT' in json.dumps(r) or 'CLI_NEW_INPUT' in json.dumps(r)]
+ assert new and all('OLD_HISTORY' in json.dumps(r) for r in new)
+ return {'historical_id': sid, 'legacy_row': old, 'first_resume': first, 'bot_retry': retry,
+ 'restart_resume': resumed, 'requests': peer.requests, 'admissions': query('SELECT * FROM session_admissions')}
+ finally:
+ peer.release.set(); peer.shutdown(); peer.server_close()
+
+
+if __name__ == '__main__':
+ output = probe(Path(sys.argv[1]), Path(sys.argv[2]))
+ (Path(sys.argv[1]) / 'receipt.json').write_text(json.dumps(output, indent=2))
+ print(json.dumps({'historical_id': output['historical_id'], 'admissions': len(output['admissions'])}))
diff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.py
new file mode 100644
index 00000000000..e2916b97ad3
--- /dev/null
+++ b/tests/gateway/test_legacy_session_migration.py
@@ -0,0 +1,113 @@
+"""Pre-authority rows never grant ownership to the first remote claimant."""
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_legacy_history_adoption_is_native_owned_atomic_and_retryable(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local_title import resolve_titled_session
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import RuntimeStoreError
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ config = {'platform_toolsets': {'cli': []}}
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: config)
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ # The old CLI persisted these columns, not a fabricated canonical receipt.
+ db.create_session('old-cli', source='cli', model='old-model', cwd=str(tmp_path))
+ db.set_session_title('old-cli', 'My retained work')
+ db.append_message('old-cli', role='user', content='OLD_QUESTION')
+ db.append_message('old-cli', role='assistant', content='OLD_ANSWER')
+ db.end_session('old-cli', 'cli_exit')
+ original = db.get_session('old-cli')
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='first')
+ caps = frozenset({'session:create', 'session:read', 'session:submit'})
+ remote = Principal('remote', str(tmp_path), caps, 'remote-socket')
+ native = Principal('native', str(tmp_path), caps, 'native-socket')
+ authority._native_legacy_transports = {native.transport_id: native}
+ with pytest.raises(RuntimeStoreError, match='not_found'):
+ resolve_titled_session(authority, remote, 'My retained work')
+ assert db.get_session('old-cli') == original
+ ref = resolve_titled_session(authority, native, 'My retained work')
+ assert ref == resolve_titled_session(authority, native, 'old-cli')
+ snapshot = await authority.attach(native, ref)
+ assert [m['content'] for m in snapshot.history] == ['OLD_QUESTION', 'OLD_ANSWER']
+ receipt = local_receipt(db, ref.session_id)
+ assert ref.session_id == 'old-cli'
+ assert receipt['entry']['session_id'] == 'old-cli'
+ assert db.get_session('old-cli')['ended_at'] is None
+ assert db.get_session('old-cli')['title'] == original['title']
+ assert db.get_session('old-cli')['parent_session_id'] == original['parent_session_id']
+ policy = runner.adapters[Platform.LOCAL].policies[ref.session_id]
+ assert policy.model == 'old-model' and policy.cwd == str(tmp_path)
+ config['platform_toolsets']['cli'] = ['terminal']
+ authority.sessions.clear()
+ await authority.attach(native, ref)
+ assert runner.adapters[Platform.LOCAL].policies[ref.session_id] == policy
+ history = [{'role': 'user', 'content': 'COMPRESSED'}, {'role': 'assistant', 'content': 'RETAINED'}]
+ assert db.try_acquire_compression_lock(ref.session_id, 'fixture')
+ try:
+ db.publish_compression_child(parent_session_id=ref.session_id, child_session_id='compressed',
+ source='cli', messages=history, compression_lock_holder='fixture')
+ finally:
+ db.release_compression_lock(ref.session_id, 'fixture')
+ snapshot = await authority.attach(native, ref)
+ assert [m['content'] for m in snapshot.history] == ['COMPRESSED', 'RETAINED']
+ assert resolve_titled_session(authority, native, 'old-cli') == ref
+ assert local_receipt(db, ref.session_id)['policy'] == receipt['policy']
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ await authority.attach(remote, ref)
+ foreign = Principal(native.subject, '/foreign', caps, native.transport_id)
+ with pytest.raises(RuntimeStoreError, match='profile_mismatch'):
+ await authority.attach(foreign, ref)
+ db._write_sql('UPDATE state_meta SET value=? WHERE key=?', ('{}', 'gateway.local_policy.v1:' + ref.session_id))
+ authority.sessions.clear()
+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):
+ resolve_titled_session(authority, native, 'old-cli')
+
+
+async def test_legacy_adoption_refuses_live_owner_and_foreign_profile_without_writes(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local_title import resolve_titled_session
+ from hermes_cli.active_sessions import try_acquire_active_session, release_active_session
+ from hermes_state_runtime import RuntimeStoreError
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ db.create_session('old-live', source='cli', model='old', cwd=str(tmp_path))
+ db.create_session('foreign', source='cli', model='old', cwd=str(tmp_path), profile_name='other')
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='first')
+ native = Principal('native', str(tmp_path), frozenset({'session:read', 'session:create'}), 'socket')
+ authority._native_legacy_transports = {native.transport_id: native}
+ lease, refusal = try_acquire_active_session(session_id='old-live', surface='cli', registry_home=Path(db.db_path).parent, config={})
+ assert lease is not None, refusal
+ from hermes_cli.active_sessions import active_session_liveness_guard
+ with active_session_liveness_guard('old-live', registry_home=Path(db.db_path).parent) as active:
+ assert active
+ try:
+ with pytest.raises(RuntimeStoreError, match='runtime_coordination_required'):
+ resolve_titled_session(authority, native, 'old-live')
+ with pytest.raises(RuntimeStoreError, match='not_found'):
+ resolve_titled_session(authority, native, 'foreign')
+ with db._read_ctx() as conn:
+ assert not conn.execute("SELECT 1 FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%'").fetchall()
+ finally:
+ release_active_session(lease)
+ assert resolve_titled_session(authority, native, 'old-live')