Skip to content

The agent that grows with you

fix: import parent links and chain deletes stay inside the actor's history

Tekniumc5ea1989c554
diff --git a/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.py
index ba5acdf0bb2..bc864bd9808 100644
--- a/hermes_state_mutation_binding.py
+++ b/hermes_state_mutation_binding.py
@@ -36,3 +36,30 @@ def authorize_history(conn, actor, session_id, *, claim=False):
if claim:
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, binding))
return True
+
+
+def history_binding(conn, session_id):
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (BINDING_PREFIX + session_id,)).fetchone()
+ return saved[0] if saved else None
+
+
+def same_history_owner(conn, anchor_id, session_id):
+ """Whether chain member ``session_id`` is history the authorizer of ``anchor_id`` controls.
+
+ A real compression continuation copies its parent's route columns, so a routed member must
+ carry the anchor's exact (user_id, session_key, chat_id). A routeless member needs the
+ anchor's exact import binding; unbound, it must also pass :func:`authorize_history`'s local
+ rule (local source, no foreign user_id) — e.g. the pre-adoption ancestors of an adopted
+ legacy CLI conversation. A bound (imported) anchor therefore never reaches unbound rows.
+ """
+ columns = 'SELECT source,user_id,session_key,chat_id,origin_json FROM sessions WHERE id=?'
+ anchor, row = (conn.execute(columns, (sid,)).fetchone() for sid in (anchor_id, session_id))
+ if anchor is None or row is None:
+ return False
+ if row['session_key'] or row['chat_id'] or row['origin_json']:
+ return tuple(row)[1:4] == tuple(anchor)[1:4]
+ binding = history_binding(conn, session_id)
+ if binding != history_binding(conn, anchor_id):
+ return False
+ return binding is not None or (
+ row['source'] in {'cli', 'tui', 'gui', 'import'} and row['user_id'] in (None, '', anchor['user_id']))
diff --git a/hermes_state_mutation_guards.py b/hermes_state_mutation_guards.py
index 85e0bc9715e..96664daa9a3 100644
--- a/hermes_state_mutation_guards.py
+++ b/hermes_state_mutation_guards.py
@@ -72,9 +72,14 @@ def delete_targets(conn, session_id):
# message on the route re-admits the "deleted" conversation through the surviving child.
# The walk also runs BACKWARD to the root (#57543): a sidebar row carries the chain tip's
# id, and a surviving root re-projects as the "deleted" conversation on the next reload.
+ # Every walked row must belong to the requested row's principal domain: only that row was
+ # authorized, so a parent link into another principal's chain (an imported or forged edge)
+ # stops the walk instead of deleting their conversation.
+ from hermes_state_mutation_binding import same_history_owner
frontier = list(targets)
for _ in range(_CHAIN_CAP):
- frontier = [sid for sid in _expand_compression_lineage_ids(conn, frontier) if sid not in targets]
+ frontier = [sid for sid in _expand_compression_lineage_ids(conn, frontier)
+ if sid not in targets and same_history_owner(conn, session_id, sid)]
if not frontier:
break
targets.update(frontier)
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index 22559d438d8..05332456520 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -118,6 +118,16 @@ def _import(db, conn, session_id, payload):
if raw.get('parent_session_id'):
parents.append((sid, raw['parent_session_id']))
imported.append(sid)
- detached = db._attach_import_parents(conn, parents)
+ # A parent outside this payload is kept only when it is history this importer already
+ # controls: its import binding equals the child's (written by import_history_control in this
+ # transaction). Linking under any other row would graft the import onto a foreign chain,
+ # which a later chain-aware delete of the import would then remove.
+ from hermes_state_mutation_binding import history_binding
+ # Rows imported now, not payload ids: a payload naming an existing foreign id skips that row.
+ fresh = set(imported)
+ foreign = [(sid, parent) for sid, parent in parents if parent not in fresh and (
+ history_binding(conn, parent) is None or history_binding(conn, parent) != history_binding(conn, sid))]
+ parents = [link for link in parents if link not in foreign]
+ detached = db._attach_import_parents(conn, parents) + len(foreign)
return set(imported), {'ok': True, 'imported': len(imported), 'skipped': len(skipped),
'imported_ids': imported, 'skipped_ids': skipped, 'detached': detached, 'errors': []}
diff --git a/tests/gateway/test_session_import_chain_ownership.py b/tests/gateway/test_session_import_chain_ownership.py
new file mode 100644
index 00000000000..6f62a04fdab
--- /dev/null
+++ b/tests/gateway/test_session_import_chain_ownership.py
@@ -0,0 +1,55 @@
+"""Import parent links and chain-aware deletes never cross principals (review M4)."""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_authority import SessionAuthority
+from gateway.session_contract import Principal, SessionRef
+from gateway.session_mutations import mutate_session
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch
+
+_CAPS = frozenset({'session:read', 'session:control', 'session:create'})
+
+
+async def test_foreign_compressed_root_survives_import_and_delete_of_a_child(tmp_path):
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id='p', instance_id='owner',
+ db=db, epoch=begin_runtime_epoch(db, instance_id='owner'))
+ attacker, victim = (Principal(name, 'p', _CAPS, name) for name in ('attacker', 'victim'))
+
+ async def mutate(actor, sid, request_id, operation, payload):
+ row = db.get_session(sid) or {'runtime_revision': 0, 'runtime_generation': 0}
+ params = {'session_id': sid, 'request_id': request_id, 'expected_revision': row['runtime_revision'],
+ 'operation': operation, 'payload': payload}
+ if operation == 'delete':
+ params['expected_generation'] = row['runtime_generation']
+ return await mutate_session(authority, actor, SessionRef('p', sid), params)
+
+ # A messaging conversation another principal owns, compressed once.
+ route = dict(source='telegram', session_key='agent:main:telegram:dm:7', chat_id='7', user_id='7')
+ db.create_session('victim_root', **route)
+ db.end_session('victim_root', 'compression')
+ db.create_session('victim_tip', parent_session_id='victim_root', **route)
+ # Imported history bound to the victim principal, also a compression chain.
+ await mutate(victim, 'v_root', 'victim-import', 'import', {'sessions': [
+ {'id': 'v_root', 'source': 'cli', 'end_reason': 'compression'},
+ {'id': 'v_tip', 'source': 'cli', 'parent_session_id': 'v_root'}]})
+
+ imported = await mutate(attacker, 'att', 'attack', 'import', {'sessions': [
+ {'id': 'att', 'source': 'cli', 'parent_session_id': 'victim_root'},
+ {'id': 'att2', 'source': 'cli', 'parent_session_id': 'v_root'}]})
+ assert imported['detached'] == 2
+ assert db.get_session('att')['parent_session_id'] is None
+ assert db.get_session('att2')['parent_session_id'] is None
+ assert (await mutate(attacker, 'att', 'delete', 'delete', {}))['deleted_ids'] == ['att']
+
+ # Links forged before this guard (or by an offline ``hermes sessions import``) never carry a
+ # delete into a chain the actor is not authorized for: the walk stops at the foreign row.
+ db._execute_write(lambda c: c.execute("UPDATE sessions SET parent_session_id='v_root' WHERE id='att2'"))
+ assert (await mutate(attacker, 'att2', 'delete2', 'delete', {}))['deleted_ids'] == ['att2']
+ await mutate(attacker, 'att3', 'attack3', 'import', {'sessions': [{'id': 'att3', 'source': 'cli'}]})
+ db._execute_write(lambda c: c.execute("UPDATE sessions SET parent_session_id='victim_root' WHERE id='att3'"))
+ assert (await mutate(attacker, 'att3', 'delete3', 'delete', {}))['deleted_ids'] == ['att3']
+ assert all(db.get_session(sid) for sid in ('victim_root', 'victim_tip', 'v_root', 'v_tip'))