The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a selected-message branch copies only the requested prefix
Teknium29ae244e7c59
diff --git a/hermes_state_mutation_branch.py b/hermes_state_mutation_branch.pyindex 24613c8c44c..b95443ba6c0 100644--- a/hermes_state_mutation_branch.py+++ b/hermes_state_mutation_branch.py@@ -9,6 +9,28 @@ from hermes_state_runtime import RuntimeStoreError, _jsonfrom hermes_state_titles import lineage_title_on_conn+def _branch_boundary(conn, target, through):+ """Highest row id the branch copies. ``through`` must name an active row of the physical+ target (after compression that is the continuation, whose ids the viewer was shown); rows+ appended later, even in this same commit window, have larger ids and stay out. The tool+ results that directly follow an assistant boundary answer its calls, so they belong to it."""+ if through is None:+ return conn.execute('SELECT COALESCE(MAX(id), 0) FROM messages WHERE session_id=? AND active=1',+ (target,)).fetchone()[0]+ row = conn.execute('SELECT role FROM messages WHERE id=? AND session_id=? AND active=1',+ (through, target)).fetchone()+ if row is None:+ raise RuntimeStoreError('invalid_params')+ if row['role'] == 'assistant':+ following = conn.execute('SELECT id, role FROM messages WHERE session_id=? AND active=1 AND id>? '+ 'ORDER BY id', (target, through))+ for later in following:+ if later['role'] != 'tool':+ break+ through = later['id']+ return through++def branch_in_transaction(db, conn, session_id, payload):row = conn.execute('SELECT value FROM state_meta WHERE key=?',(POLICY_PREFIX + session_id,)).fetchone()@@ -41,7 +63,8 @@ def branch_in_transaction(db, conn, session_id, payload):conn.execute('UPDATE sessions SET session_key=?,chat_id=?,origin_json=?,system_prompt_hash=? WHERE id=?',(route, child, _json(source.to_dict()), parent['system_prompt_hash'], child))ids, tools = db._tail_rows_after_watermark(conn,- 'SELECT id,tool_calls FROM messages WHERE session_id=? AND active=1 ORDER BY id', [target])+ 'SELECT id,tool_calls FROM messages WHERE session_id=? AND active=1 AND id<=? ORDER BY id',+ [target, _branch_boundary(conn, target, payload.get('through_message_id'))])db._clone_message_rows(conn, ids, session_id=child)conn.execute('UPDATE sessions SET message_count=?,tool_call_count=? WHERE id=?', (len(ids), tools, child))if payload.get('title'):diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex 18e6bdb11e6..81b14ffe359 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -12,7 +12,7 @@ def validate_action(operation, payload):if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider', 'confirm'}and all(isinstance(v, str) and v.strip() for v in payload.values())):return- if operation == 'branch' and (not payload or (set(payload) == {'title'} and isinstance(payload['title'], str))):+ if operation == 'branch' and _valid_branch_payload(payload):returnif operation == 'compress' and _valid_compress_payload(payload):return@@ -34,6 +34,17 @@ def validate_action(operation, payload):raise RuntimeStoreError('invalid_params')+def _valid_branch_payload(payload):+ # ``through_message_id``: the physical row id of the last message the branch keeps (a stable+ # boundary, never a visible-message count); absent means the whole active transcript.+ if set(payload) - {'title', 'through_message_id'}:+ return False+ if 'title' in payload and not isinstance(payload['title'], str):+ return False+ return 'through_message_id' not in payload or (+ type(payload['through_message_id']) is int and payload['through_message_id'] > 0)++_COMPRESS_FIELDS = {'focus': str, 'preview': bool, 'partial': bool, 'keep_last': int}diff --git a/tests/gateway/test_session_mutation_branch_boundary.py b/tests/gateway/test_session_mutation_branch_boundary.pynew file mode 100644index 00000000000..871db17d7c0--- /dev/null+++ b/tests/gateway/test_session_mutation_branch_boundary.py@@ -0,0 +1,71 @@+"""A selected-message branch copies exactly the requested prefix (helix4u #5).++Desktop branches from a chosen message; the canonical branch used to clone every active parent+row, so later instructions and answers the user meant to leave behind rode into the child. The+boundary is a physical row id (``through_message_id``), validated against the parent's active+transcript inside the receipt transaction and part of the retry identity.+"""+from types import SimpleNamespace++import pytest++from gateway.session_authority import SessionAuthority+from gateway.session_controls import AuthorityConnection+from gateway.session_local import create_local_session+import hermes_state_runtime as rt+++async def test_branch_through_a_middle_message_excludes_later_and_concurrent_rows(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore++ monkeypatch.setattr(run, '_load_gateway_config', dict)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _adapter_for_source=lambda source: None)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ ref = create_local_session(authority, owner.actor, dict(request_id='branch-boundary', source='cli',+ cwd=str(tmp_path), model='m', toolsets=[]))+ sid = ref.session_id+ db.append_message(sid, 'user', 'KEEP question')+ call = [{'id': 'c1', 'type': 'function', 'function': {'name': 'read_file', 'arguments': '{}'}}]+ boundary = db.append_message(sid, 'assistant', 'KEEP reading', tool_calls=call)+ db.append_message(sid, 'tool', 'KEEP tool result', tool_call_id='c1')+ db.append_message(sid, 'user', 'DROP later instruction')+ db.append_message(sid, 'assistant', 'DROP later answer')+ session = db.get_session(sid)++ async def mutate(request_id, payload):+ return await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': sid, 'request_id': request_id, 'expected_revision': session['runtime_revision'],+ 'expected_generation': session['runtime_generation'], 'operation': 'branch', 'payload': payload}})++ try:+ # A message that lands between the click and the commit (a concurrent turn) is later too.+ db.append_message(sid, 'user', 'DROP concurrent message')+ reply = await mutate('pick', {'through_message_id': boundary})+ receipt = reply['result']+ child = receipt['branched_session_id']+ # The assistant boundary keeps the tool result that answers its call, nothing after it.+ assert [m['content'] for m in db.get_messages_as_conversation(child)] == [+ 'KEEP question', 'KEEP reading', 'KEEP tool result']+ assert receipt['copied_messages'] == 3+ # Exact retry: the same child, even though the parent kept growing.+ db.append_message(sid, 'assistant', 'DROP after commit')+ assert (await mutate('pick', {'through_message_id': boundary}))['result'] == receipt+ # The boundary is retry identity: the same request id with another boundary is a conflict.+ conflict = await mutate('pick', {'through_message_id': boundary + 1})+ assert conflict['error']['message'] == 'admission_conflict'+ # A row that is not in this session's active transcript is refused, not silently widened.+ foreign = db.append_message(child, 'user', 'child row')+ session = db.get_session(sid)+ refused = await mutate('foreign', {'through_message_id': foreign})+ assert refused['error']['message'] == 'invalid_params', refused+ finally:+ await owner.close()diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 742e637ddca..512e3a113ce 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -217,7 +217,10 @@ different contents returns `admission_conflict`. A competing edit with a stalerevision returns `revision_conflict`. Draining rejects new mutations and freshsession registration before routing or transcript creation. These editsdo not interrupt a running turn. Canonical reset, delete, rewind, model, branch,-and compression operations use the same receipt boundary. A request disconnect+and compression operations use the same receipt boundary. `branch` accepts an optional+`title` and `through_message_id` (the row id of the last message to keep; tool results+answering an assistant boundary come with it); without it the whole active transcript is+copied. A request disconnectdoes not cancel its owner-held mutation: the commit, live projection and queuewakeup finish together, and profile retirement joins that work before releasingthe store. An exact old receipt cannot evict a newer running agent.