The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): the managed worker's store answers every session_db read the agent core makes
Teknium3c34e12465c0
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex db6e7d4a50f..1238d71990e 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -302,6 +302,16 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecycldef get_session_title(self, session_id):return self.get_session(session_id).get('title')+ # Transcript-tail reads the agent core makes on its session_db (failed-turn boundary, in-place+ # compaction coverage); a missing one raised AttributeError inside a best-effort guard.+ def latest_conversation_role(self, session_id):+ self._session(session_id)+ return self._apply('session.tail_role', {})['value']++ def get_message_role(self, session_id, row_id):+ self._session(session_id)+ return self._apply('session.row_role', {'row_id': int(row_id)})['value']+def get_compression_failure_cooldown_row(self, session_id):row = self.get_session(session_id)return {'session_exists': True, 'cooldown_until': row.get('compression_failure_cooldown_until'),diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex cc6a246c3f7..87539e6f542 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -649,7 +649,8 @@ def _worker_finish(db, conn, session_id, payload):def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,sequence, operation, payload):"""One closed durable mutation and receipt; never call a self-committing API here."""- from hermes_state_worker_context import worker_context, worker_prompt, worker_sidecars, worker_tool_names+ from hermes_state_worker_context import (worker_context, worker_prompt, worker_row_role, worker_sidecars,+ worker_tail_role, worker_tool_names)from hermes_state_worker_compression import WORKER_COMPRESSION_HANDLERSfrom hermes_state_worker_lifecycle import WORKER_LIFECYCLE_HANDLERShandlers = {@@ -659,6 +660,8 @@ def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,'session.prompt': worker_prompt,'session.sidecars': worker_sidecars,'session.tools': worker_tool_names,+ 'session.tail_role': worker_tail_role,+ 'session.row_role': worker_row_role,'transcript.append': _worker_append,'execution.finish': _worker_finish,'usage.main': _worker_usage,diff --git a/hermes_state_worker_context.py b/hermes_state_worker_context.pyindex 4fc72322590..b132aa4137e 100644--- a/hermes_state_worker_context.py+++ b/hermes_state_worker_context.py@@ -66,3 +66,21 @@ def worker_tool_names(db, conn, session_id, payload):(db._store_system_prompt(conn, encoded), session_id))db._delete_unreferenced_system_prompts(conn)return {'value': None}+++def worker_tail_role(db, conn, session_id, payload):+ """``SessionDB.latest_conversation_role`` on the receipt connection (failed-turn boundary)."""+ if payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute("SELECT role FROM messages WHERE session_id=? AND active=1 "+ "AND role NOT IN ('session_meta','system') ORDER BY id DESC LIMIT 1", (session_id,)).fetchone()+ return {'value': row[0] if row else None}+++def worker_row_role(db, conn, session_id, payload):+ """``SessionDB.get_message_role``: the role of an active row of THIS transcript, else None."""+ if set(payload) != {'row_id'} or type(payload['row_id']) is not int:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute('SELECT role FROM messages WHERE id=? AND session_id=? AND active=1',+ (payload['row_id'], session_id)).fetchone()+ return {'value': row[0] if row else None}diff --git a/tests/agent/test_runtime_session_store_surface_parity.py b/tests/agent/test_runtime_session_store_surface_parity.pynew file mode 100644index 00000000000..2ffb4053496--- /dev/null+++ b/tests/agent/test_runtime_session_store_surface_parity.py@@ -0,0 +1,68 @@+"""A managed worker's agent gets a RuntimeSessionStore as its session_db. Every SessionDB method+the agent core calls must exist on the store, accept the same keywords, and answer like the+owner's SessionDB (Adolanium reg-1 was one missing keyword; the sweep found two missing reads:+the failed-turn boundary's tail role and in-place compaction's held-row liveness)."""+import ast+import inspect+from pathlib import Path+import re++import pytest++from agent.runtime_session_store import RuntimeSessionStore+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch, mutate_worker_execution, register_worker_execution++ROOT = Path(__file__).resolve().parents[2]+# The agent core: everything a worker's AIAgent runs (tools open their own handles, or refuse).+CORE = [ROOT / 'run_agent.py', *sorted((ROOT / 'agent').glob('*.py'))]+++def _core_session_db_calls():+ """Names called on the agent's store: ``x._session_db`` / ``x.db`` / ``session_db``, and a local+ ``db`` where the module binds it from ``_session_db`` (a module opening its own SessionDB is not)."""+ names = set()+ for path in CORE:+ text = path.read_text(encoding='utf-8')+ local_db = re.search(r'\bdb\b[^=\n]*=\s*getattr\([^)\n]*_session_db', text) is not None+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):+ owner = node.func.value+ if ((isinstance(owner, ast.Attribute) and owner.attr in ('_session_db', 'db'))+ or (isinstance(owner, ast.Name) and (owner.id == 'session_db' or (owner.id == 'db' and local_db)))):+ names.add(node.func.attr)+ return sorted(n for n in names if hasattr(SessionDB, n))++[email protected]('name', _core_session_db_calls())+def test_store_offers_every_core_session_db_call_with_its_keywords(name):+ assert hasattr(RuntimeSessionStore, name), f'RuntimeSessionStore lacks {name}'+ store = inspect.signature(getattr(RuntimeSessionStore, name)).parameters+ if any(p.kind is p.VAR_KEYWORD for p in store.values()):+ return+ owner = inspect.signature(getattr(SessionDB, name)).parameters+ missing = [k for k, p in owner.items() if k not in store and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)]+ assert missing == [], f'RuntimeSessionStore.{name} rejects {missing}'+++def test_tail_reads_answer_like_the_owner(tmp_path):+ db = SessionDB(tmp_path / 'state.db')+ try:+ db.create_session('s', 'cli')+ db.append_messages_batch('s', [{'role': 'user', 'content': 'q'}, {'role': 'assistant', 'content': 'a'},+ {'role': 'user', 'content': 'failed turn'}])+ db.create_session('other', 'cli')+ db.append_messages_batch('other', [{'role': 'assistant', 'content': 'x'}])+ rows = [r[0] for r in db._read_all('SELECT id FROM messages ORDER BY id')]+ epoch = begin_runtime_epoch(db, instance_id='fixture')+ scope = dict(epoch=epoch, execution_id='w', session_id='s', generation=0)+ register_worker_execution(db, **scope, kind='compute', adoption_secret='secret')+ store = RuntimeSessionStore(lambda method, **p: mutate_worker_execution(db, **p), scope, tmp_path / 'outbox')+ try:+ assert store.latest_conversation_role('s') == db.latest_conversation_role('s') == 'user'+ for row_id in [*rows, 10**6]: # another transcript's row is not this session's+ assert store.get_message_role('s', row_id) == db.get_message_role('s', row_id)+ finally:+ store.close()+ finally:+ db.close()