The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a served profile's delivery-ledger rows in the launch state.db
John Paul Soliva4d3815d7c2f5
diff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.pyindex d83738bc747..05f164e405a 100644--- a/gateway/delivery_ledger.py+++ b/gateway/delivery_ledger.py@@ -23,7 +23,7 @@ from typing import Any, Dict, List, Optionalfrom gateway.dead_targets import classify_dead_errorfrom hermes_cli.sqlite_util import add_column_if_missing-from hermes_constants import get_hermes_home+from hermes_constants import get_process_hermes_homelogger = logging.getLogger(__name__)_DB_LOCK = threading.Lock()@@ -169,7 +169,11 @@ def retry_not_before(updated_at: Any, last_error: Any, attempts: Any) -> Optionadef _db_path():- return get_hermes_home() / "state.db"+ # Launch home, not get_hermes_home(): a multiplexed gateway records a served profile's replies+ # under that profile's home override, but the boot sweep reads from the launch context, so both+ # must open the one shared store (adapter_profile tells the bots apart). No get_hermes_home()+ # fallback for an unset HERMES_HOME: a default gateway run in the foreground has none.+ return get_process_hermes_home() / "state.db"def _connect() -> sqlite3.Connection:diff --git a/tests/gateway/test_delivery_ledger_process_home.py b/tests/gateway/test_delivery_ledger_process_home.pynew file mode 100644index 00000000000..b071e71385e--- /dev/null+++ b/tests/gateway/test_delivery_ledger_process_home.py@@ -0,0 +1,103 @@+"""A served profile's reply is ledgered where the boot sweep looks for it.++A multiplexed gateway connects each served profile's adapter inside that profile's home override+(``_profile_runtime_scope``), and the receive loop the adapter starts while connecting inherits it,+so every final reply that bot sends is recorded from that context. The boot sweep that redelivers a+reply cut off by a crash runs in the launch context. The ledger used to resolve its path through+``get_hermes_home()``, which follows the override: the row landed in ``profiles/<name>/state.db``,+the sweep opened the launch ``state.db``, and the reply was never redelivered.++Every other ledger test replaces ``_db_path``; these leave it alone, since the path is what is+under test.+"""++from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock, MagicMock++import pytest++import hermes_constants+from gateway import delivery_ledger as dl+from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, SendResult+from gateway.platforms.event import MessageEvent, MessageType+from gateway.session import SessionSource++SESSION_KEY = "agent:research:slack:channel:C1"+ANSWER = "the final answer"+++class _ServedAdapter(BasePlatformAdapter):+ """The served profile's own bot; its sends succeed, so the ledger is all that is observed."""++ def __init__(self):+ super().__init__(PlatformConfig(enabled=True), Platform.SLACK)+ self._owner_profile = "research"+ self.sent = []++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ return True++ async def disconnect(self) -> None:+ return None++ async def get_chat_info(self, chat_id):+ return {}++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent.append(content)+ return SendResult(success=True, message_id="m-2")++[email protected](params=["hermes-home-env", "platform-default"])+def launch_home(request, tmp_path, monkeypatch):+ root = tmp_path / "root"+ (root / "profiles" / "research").mkdir(parents=True)+ if request.param == "hermes-home-env":+ monkeypatch.setenv("HERMES_HOME", str(root))+ else:+ # A default gateway run in the foreground has no HERMES_HOME at all.+ monkeypatch.delenv("HERMES_HOME", raising=False)+ monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: root)+ return root+++def _runner(adapter):+ from gateway.run import GatewayRunner++ runner = object.__new__(GatewayRunner)+ runner.adapters = {}+ runner._profile_adapters = {"research": {Platform.SLACK: adapter}}+ runner._active_profile_name = lambda: "default"+ store = MagicMock()+ store.clear_resume_pending = AsyncMock()+ store._store = None+ runner.session_store = None+ runner._async_session_store = store+ return runner+++async def test_boot_sweep_redelivers_a_reply_recorded_under_a_served_profile_scope(launch_home):+ from gateway.run import _profile_runtime_scope++ adapter = _ServedAdapter()+ event = MessageEvent(+ text="hi", message_type=MessageType.TEXT, message_id="m-1",+ source=SessionSource(platform=Platform.SLACK, chat_id="C1", chat_type="channel"))+ # Stands in for the receive loop: a task created while the adapter connects under the scope.+ with _profile_runtime_scope(launch_home / "profiles" / "research", hydrate_secrets=False):+ record = asyncio.create_task(+ adapter._record_delivery_obligation(event, SESSION_KEY, ANSWER, adapter, False))+ assert await record++ # The gateway died after the send began and before the platform acknowledged it.+ with dl._connect() as conn:+ conn.execute("UPDATE delivery_obligations SET owner_pid=999999999, owner_started_at=1")++ runner = _runner(adapter)+ assert await runner._redeliver_pending_obligations() == 1+ assert adapter.sent == [dl.RECOVERED_MARKER + ANSWER]+ runner._async_session_store.clear_resume_pending.assert_awaited_once_with(SESSION_KEY)diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.mdindex 50310d90798..8466f1fa5f0 100644--- a/website/docs/user-guide/messaging/index.md+++ b/website/docs/user-guide/messaging/index.md@@ -281,7 +281,8 @@ Final agent responses are recorded in a durable **delivery ledger**(`state.db`) around each platform send. If the gateway crashes or restartsbetween producing a response and the platform confirming receipt, the nextboot redelivers the stored response instead of losing it — or re-running the-whole turn.+whole turn. The ledger lives in the home the gateway was started from; a+multiplexed gateway keeps every served profile's replies there too.Semantics are honest at-least-once: