hermes_state_mutation_branch.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """An independent local route, transcript and frozen policy in one receipt commit."""
  2. import json
  3. import uuid
  4. from hermes_state_local import POLICY_PREFIX
  5. from hermes_state_local_lineage import validate_local_lineage
  6. from hermes_state_mutation_guards import require_idle
  7. from hermes_state_runtime import RuntimeStoreError, _json
  8. from hermes_state_titles import lineage_title_on_conn
  9. def _branch_boundary(conn, target, through):
  10. """Highest row id the branch copies. ``through`` must name an active row of the physical
  11. target (after compression that is the continuation, whose ids the viewer was shown); rows
  12. appended later, even in this same commit window, have larger ids and stay out. The tool
  13. results that directly follow an assistant boundary answer its calls, so they belong to it."""
  14. if through is None:
  15. return conn.execute('SELECT COALESCE(MAX(id), 0) FROM messages WHERE session_id=? AND active=1',
  16. (target,)).fetchone()[0]
  17. row = conn.execute('SELECT role FROM messages WHERE id=? AND session_id=? AND active=1',
  18. (through, target)).fetchone()
  19. if row is None:
  20. raise RuntimeStoreError('invalid_params')
  21. if row['role'] == 'assistant':
  22. following = conn.execute('SELECT id, role FROM messages WHERE session_id=? AND active=1 AND id>? '
  23. 'ORDER BY id', (target, through))
  24. for later in following:
  25. if later['role'] != 'tool':
  26. break
  27. through = later['id']
  28. return through
  29. def _child_policy(policy, child, prepared):
  30. """The parent's frozen policy, except editor MCP servers: the gateway prepared the child's own
  31. selection under the child's own scope (gateway/session_local_mcp.py ``prepare_branch_editor``).
  32. Copying the parent's would share its scope, borrowed credentials and live connections.
  33. A branch starts at Default (``ask``), as main's ACP ``fork_session`` did."""
  34. if 'edit_approval_policy' in policy:
  35. policy = {**policy, 'edit_approval_policy': 'ask'}
  36. if prepared is None:
  37. if policy.get('editor_mcp_json'):
  38. raise RuntimeStoreError('runtime_coordination_required')
  39. return policy
  40. # Prepared against the parent's selection and the child id this commit derives; anything else moved.
  41. if child != prepared['child'] or policy.get('editor_mcp_json') != prepared['parent_editor_mcp_json']:
  42. raise RuntimeStoreError('revision_conflict')
  43. return {**policy, 'editor_mcp_json': prepared['editor_mcp_json'], 'toolsets': prepared['toolsets'],
  44. 'config_secret_ref': prepared['config_secret_ref']}
  45. def branch_in_transaction(db, conn, session_id, payload, prepared=None):
  46. row = conn.execute('SELECT value FROM state_meta WHERE key=?',
  47. (POLICY_PREFIX + session_id,)).fetchone()
  48. if row is None:
  49. raise RuntimeStoreError('runtime_coordination_required')
  50. saved = json.loads(row[0])
  51. target = validate_local_lineage(conn, saved)
  52. require_idle(db, conn, list({session_id, target}))
  53. # Late: the routing entry/key are gateway types (the gateway imports this store at module level).
  54. from gateway.session import SessionEntry, SessionSource
  55. from gateway.config import Platform
  56. from hermes_state_keys import local_identity, profile_from_session_key
  57. request_id = prepared['request_id'] if prepared else 'branch:' + uuid.uuid4().hex
  58. child = local_identity(saved['profile_id'], saved['principal_id'], request_id)
  59. policy = _child_policy(saved['policy'], child, prepared)
  60. # The child keeps the parent's owning profile: a served secondary's origin names it
  61. # (``local_source``), and restore compares the stored origin against that exactly.
  62. source = SessionSource(Platform.LOCAL, child, user_id=saved['principal_id'], chat_type='dm',
  63. profile=saved['entry']['origin'].get('profile'))
  64. from gateway.session import build_session_key
  65. route = build_session_key(source, profile=profile_from_session_key(saved['route']))
  66. from gateway.session_lifecycle import _now
  67. now = _now()
  68. entry = SessionEntry(route, child, now, now, origin=source, platform=Platform.LOCAL)
  69. parent = conn.execute('SELECT * FROM sessions WHERE id=?', (target,)).fetchone()
  70. db._publish_child_session_row(conn, parent, parent_session_id=target,
  71. child_session_id=child, source=policy['source'], model=policy['model'],
  72. model_config={'_branched_from': target}, system_prompt=None,
  73. cwd=policy['cwd'], profile_name=parent['profile_name'])
  74. conn.execute('UPDATE sessions SET session_key=?,chat_id=?,origin_json=?,system_prompt_hash=? WHERE id=?',
  75. (route, child, _json(source.to_dict()), parent['system_prompt_hash'], child))
  76. ids, tools = db._tail_rows_after_watermark(conn,
  77. 'SELECT id,tool_calls FROM messages WHERE session_id=? AND active=1 AND id<=? ORDER BY id',
  78. [target, _branch_boundary(conn, target, payload.get('through_message_id'))])
  79. db._clone_message_rows(conn, ids, session_id=child)
  80. conn.execute('UPDATE sessions SET message_count=?,tool_call_count=? WHERE id=?', (len(ids), tools, child))
  81. if payload.get('title'):
  82. db._set_session_title_in_transaction(conn, child, payload['title'], source=db.TITLE_SOURCE_USER)
  83. else:
  84. # Untitled branch: the next name in the parent's lineage ("my session" → "my session #2"),
  85. # same rule as the legacy TUI /branch, so the child is its own titled sidebar row.
  86. db._set_session_title_in_transaction(conn, child, lineage_title_on_conn(conn, parent['title'] or 'branch'),
  87. source=db.TITLE_SOURCE_DERIVED)
  88. receipt = dict(profile_id=saved['profile_id'], principal_id=saved['principal_id'],
  89. request_id=request_id, session_id=child, route=route, entry=entry.to_dict(), policy=policy)
  90. # The copied policy holds the parent's picks; the child's refresh must keep them as picks, not defaults.
  91. # Always written: a receipt without it predates the field, and picks_on reads that one's lineage.
  92. from hermes_state_mutation_prepared import picks_on
  93. receipt['picks'] = sorted(picks_on(conn, session_id))
  94. conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?)",
  95. (route, _json(entry.to_dict()), now.timestamp()))
  96. conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (POLICY_PREFIX + child, _json(receipt)))
  97. return {session_id}, {'branched_session_id': child, 'copied_messages': len(ids)}