diff --git a/plugin/pheby/hermes_bridge.py b/plugin/pheby/hermes_bridge.py index c319777..ba0e988 100644 --- a/plugin/pheby/hermes_bridge.py +++ b/plugin/pheby/hermes_bridge.py @@ -206,13 +206,24 @@ async def list_conversations(server: Any = None) -> List[Dict[str, Any]]: db = _session_db() if db is not None: try: - deliveries = await asyncio.to_thread( - db._read_all, - "SELECT s.chat_id, s.id, MAX(m.timestamp) AS last_active " - "FROM sessions s JOIN messages m ON m.session_id = s.id " - "WHERE s.source = ? GROUP BY s.id, s.chat_id", - ("pheby_delivery",), + # The persistence layer no longer exposes raw SQL; the sessions + # repository's source search returns every row (archived included) + # with its computed last_active — the same recency the old + # MAX(messages.timestamp) query produced. + from persistence.conversation.sessions import SessionWindow + entries = await asyncio.to_thread( + db.sessions.search_sessions, + sources=("pheby_delivery",), + window=SessionWindow(limit=None), ) + deliveries = [ + { + "chat_id": getattr(e.session, "chat_id", None), + "id": str(getattr(e.session, "session_id", "")), + "last_active": getattr(e, "last_active", None), + } + for e in entries + ] by_id = {item["conversation_id"]: item for item in out} for row in deliveries: cid = str(row["chat_id"] or "") @@ -285,12 +296,16 @@ async def persist_cron_delivery(conversation_id: str, content: str, timestamp = time.time() def _persist() -> int: - db.create_session(sid, "pheby_delivery", session_key=key, - chat_id=conversation_id, chat_type="dm") - return db.append_message( - sid, "assistant", content, timestamp=timestamp, + from persistence.conversation.messages import NewMessage + from persistence.conversation.sessions import NewSession, SessionId + db.sessions.create(NewSession( + session_id=SessionId(sid), source="pheby_delivery", session_key=key, + chat_id=conversation_id, chat_type="dm")) + msg_id = db.messages.append(sid, NewMessage( + role="assistant", content=content, timestamp=timestamp, display_kind="cron_delivery", - display_metadata={"job_id": str(metadata["job_id"])}) + display_metadata={"job_id": str(metadata["job_id"])})) + return int(msg_id) row_id = await asyncio.to_thread(_persist) server = _current_server() @@ -334,24 +349,40 @@ async def conversation_history(conversation_id: str, limit: int, db = _session_db() if db is not None: try: - # The routing index only knows the current generation. Query the + # The routing index only knows the current generation. Search the # persisted key to include resets even when parent_session_id is - # absent. Hermes's own decoder handles archived/compacted rows. - ids = await asyncio.to_thread( - db._read_all, - "SELECT id FROM sessions WHERE session_key = ? AND source IN (?, ?) ORDER BY started_at, id", - (session_key, "pheby", "pheby_delivery"), + # absent. Raw SQL is gone from the persistence layer; the sessions + # repository's source search (no archived filter) plus a + # client-side session_key filter is the equivalent lookup. + from persistence.conversation.sessions import SessionWindow + entries = await asyncio.to_thread( + db.sessions.search_sessions, + sources=("pheby", "pheby_delivery"), + window=SessionWindow(limit=None), ) - session_ids = [str(row["id"]) for row in ids] + keyed = { + str(e.session.session_id): + (float(getattr(e.session, "started_at", 0.0) or 0.0), + str(e.session.session_id)) + for e in entries + if str(getattr(e.session, "session_key", "") or "") == str(session_key) + } + # Chronological order (the old SQL ordered by started_at, id): + # older generations must page before the current one. + session_ids = [sid for sid, _ in sorted(keyed.items(), key=lambda kv: kv[1])] if session_id and session_id not in session_ids: session_ids.append(session_id) if session_ids: found = True rows = [] + from persistence.conversation.messages import ConversationRequest, TranscriptView for sid in session_ids: - rows.extend(await asyncio.to_thread( - db.get_messages_as_conversation, sid, - include_row_ids=True, include_compacted=True)) + for msg in await asyncio.to_thread( + db.messages.read_conversation, sid, + ConversationRequest(include_row_ids=True, + view=TranscriptView.DISPLAY)): + row = msg.as_openai_message() + rows.append(row) rows.sort(key=lambda row: int(row.get("_row_id") or 0)) visible = [] seen_replays = set() @@ -453,18 +484,33 @@ async def delete_conversation(conversation_id: str) -> bool: if db is not None: try: - rows = await asyncio.to_thread( - db._read_all, - "SELECT id FROM sessions WHERE session_key = ? AND source IN (?, ?) ORDER BY started_at, id", - (session_key, "pheby", "pheby_delivery"), + from persistence.conversation.sessions import SessionWindow + entries = await asyncio.to_thread( + db.sessions.search_sessions, + sources=("pheby", "pheby_delivery"), + window=SessionWindow(limit=None), ) - ids = [str(row["id"]) for row in rows] + ids = [ + str(e.session.session_id) for e in entries + if str(getattr(e.session, "session_key", "") or "") == str(session_key) + ] if session_id and session_id not in ids: ids.append(str(session_id)) if ids: - deleted = await asyncio.to_thread(db.delete_sessions, ids) - if deleted != len(ids): - return False + from gateway.session_ingress_media import native_inputs_root + removed = set() + for target in ids: + deleted = await asyncio.to_thread( + db.sessions.delete, target, + media_root=str(native_inputs_root())) + removed.update(str(i) for i in deleted) + # Every requested id must be gone afterwards (delete() also + # removes lineage children, so removed can be a superset). + for target in ids: + if target in removed: + continue + if await asyncio.to_thread(db.sessions.get, target) is not None: + return False except Exception: logger.error("[pheby] session db delete failed", exc_info=True) return False @@ -897,9 +943,13 @@ async def yolo_snapshot(conversation_id: str) -> Dict[str, Any]: db = _session_db() if db is not None: try: - meta = await asyncio.to_thread(db.get_session, str(session_id)) - from hermes_state import SessionDB - if SessionDB.session_yolo_enabled(meta): + from persistence.conversation.sessions import ( + SessionId, + session_yolo_enabled, + ) + record = await asyncio.to_thread( + db.sessions.get, SessionId(str(session_id))) + if record is not None and session_yolo_enabled(record.model_config): enable_session_yolo(session_key) enabled = True except Exception: @@ -927,7 +977,9 @@ async def set_yolo(conversation_id: str, enabled: bool) -> Dict[str, Any]: db = _session_db() if db is not None: try: - await asyncio.to_thread(db.set_session_yolo, str(session_id), bool(enabled)) + from persistence.conversation.sessions import SessionId + await asyncio.to_thread( + db.sessions.set_yolo, SessionId(str(session_id)), bool(enabled)) except Exception: logger.warning("[pheby] yolo persistence failed", exc_info=True) return {"ok": True, "enabled": bool(enabled), "scope": "conversation", diff --git a/tests/test_cron_delivery.py b/tests/test_cron_delivery.py index 1ec113d..8b5a213 100644 --- a/tests/test_cron_delivery.py +++ b/tests/test_cron_delivery.py @@ -2,7 +2,8 @@ import pytest from gateway.config import PlatformConfig -from hermes_state import SessionDB +from persistence.conversation.messages import NewMessage +from persistence.conversation.sessions import NewSession, SessionId from pheby import hermes_bridge as hb, protocol as proto from pheby.adapter import PhebyAdapter from pheby.server import PhebyServer @@ -10,7 +11,11 @@ from pheby.server import PhebyServer @pytest.fixture def delivery_stack(tmp_path, monkeypatch): - db = SessionDB(tmp_path / "state.db") + # SessionDB is deprecated; open the storage interface directly for the + # test profile (context-local HERMES_HOME drives profile_scope()). + from persistence_assembly import open_persistence, profile_scope + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + db = open_persistence(profile_scope(), eager=True) monkeypatch.setattr(hb, "_session_db", lambda: db) monkeypatch.setattr(hb, "_session_store", lambda: None) adapter = PhebyAdapter(PlatformConfig(enabled=True, extra={"secret": "test-secret"})) @@ -30,8 +35,9 @@ async def test_cron_delivery_survives_reopen_without_touching_active_turn(delive adapter, server, db = delivery_stack cid = "home" key = hb._session_key_for(cid) - db.create_session("active-session", "pheby", session_key=key) - db.append_message("active-session", "user", "My ongoing question") + db.sessions.create(NewSession( + session_id=SessionId("active-session"), source="pheby", session_key=key)) + db.messages.append("active-session", NewMessage(role="user", content="My ongoing question")) adapter._drafts[cid] = {"message_id": "draft-active", "text": "Still thinking"} hb._ACTIVE_RUNS[cid] = {"run_id": "active-run", "started": 0} @@ -44,7 +50,7 @@ async def test_cron_delivery_survives_reopen_without_touching_active_turn(delive assert found and not has_more assert hb.active_run_id(cid) == "active-run" assert adapter._drafts[cid]["message_id"] == "draft-active" - assert [m["content"] for m in db.get_messages_as_conversation("active-session")] == ["My ongoing question"] + assert [m.content for m in db.messages.read_conversation("active-session")] == ["My ongoing question"] assert await server.router.get_name(cid) is not None conversations = await hb.list_conversations(server) assert conversations[0]["conversation_id"] == cid @@ -67,7 +73,7 @@ async def test_cron_delivery_does_not_claim_success_when_save_fails(delivery_sta raise OSError("disk unavailable") monkeypatch.setattr(server, "broadcast", broadcast) - monkeypatch.setattr(db, "append_message", fail) + monkeypatch.setattr(db.messages, "append", fail) result = await adapter.send("home", "A report", metadata={"job_id": "daily"}) assert not result.success assert broadcasts == [] diff --git a/tests/test_pheby.py b/tests/test_pheby.py index 98c025a..29fe562 100644 --- a/tests/test_pheby.py +++ b/tests/test_pheby.py @@ -452,18 +452,31 @@ class TestBridge: def peek_session_id(self, _key): return "session-1" - class DB: - def _read_all(self, sql, params): - return [{"id": "session-1"}] + class _Msg: + def __init__(self, row): + self._row = row - def get_messages_as_conversation(self, _session_id, include_row_ids=False, include_compacted=False): - assert include_row_ids is True - assert include_compacted is True + def as_openai_message(self): + return self._row + + class Sessions: + def search_sessions(self, *, sources, window): + return [] + + class Messages: + def read_conversation(self, _session_id, request): + from persistence.conversation.messages import TranscriptView + assert request.include_row_ids is True + assert request.view is TranscriptView.DISPLAY return [ - {"_row_id": 10, "role": "user", "content": "hello", "timestamp": 1_789_000_000.25}, - {"_row_id": 11, "role": "assistant", "content": "reply", "timestamp": 1_789_000_001.5}, + _Msg({"_row_id": 10, "role": "user", "content": "hello", "timestamp": 1_789_000_000.25}), + _Msg({"_row_id": 11, "role": "assistant", "content": "reply", "timestamp": 1_789_000_001.5}), ] + class DB: + sessions = Sessions() + messages = Messages() + monkeypatch.setattr(hb, "_session_store", lambda: Store()) monkeypatch.setattr(hb, "_session_db", lambda: DB()) @@ -483,17 +496,35 @@ class TestBridge: def peek_session_id(self, _key): return "new" - class DB: - def _read_all(self, sql, params): - assert "session_key" in sql and params[1] == "pheby" - return [{"id": "old"}, {"id": "new"}] + class _Msg: + def __init__(self, row): + self._row = row - def get_messages_as_conversation(self, sid, **kwargs): - assert kwargs == {"include_row_ids": True, "include_compacted": True} + def as_openai_message(self): + return self._row + + key = hb._session_key_for("conv") + + def _entry(session_id): + from types import SimpleNamespace + return SimpleNamespace(session=SimpleNamespace( + session_id=session_id, session_key=key)) + + class Sessions: + def search_sessions(self, *, sources, window): + assert "pheby" in sources + return [_entry("old"), _entry("new")] + + class Messages: + def read_conversation(self, sid, _request): start = 1 if sid == "old" else 4 - return [{"_row_id": n, "role": "user", "content": f"turn {n}", "timestamp": float(n)} + return [_Msg({"_row_id": n, "role": "user", "content": f"turn {n}", "timestamp": float(n)}) for n in range(start, start + 3)] + class DB: + sessions = Sessions() + messages = Messages() + monkeypatch.setattr(hb, "_session_store", lambda: Store()) monkeypatch.setattr(hb, "_session_db", lambda: DB()) latest, found, older = await hb.conversation_history("conv", 2) @@ -510,10 +541,13 @@ class TestBridge: async def test_history_read_failure_is_not_reported_as_empty_chat(self, monkeypatch): from pheby import hermes_bridge as hb - class DB: - def _read_all(self, _sql, _params): + class Sessions: + def search_sessions(self, *, sources, window): raise OSError("database offline") + class DB: + sessions = Sessions() + monkeypatch.setattr(hb, "_session_store", lambda: None) monkeypatch.setattr(hb, "_session_db", lambda: DB()) with pytest.raises(RuntimeError, match="transcript"): @@ -735,9 +769,15 @@ class TestBridge: assert key == session_key return "session-1" + class Sessions: + def get(self, _session_id): + return None + + def set_yolo(self, session_id, enabled): + persisted.append((str(session_id), enabled)) + class DB: - def set_session_yolo(self, session_id, enabled): - persisted.append((session_id, enabled)) + sessions = Sessions() monkeypatch.setattr(hb, "_session_store", lambda: Store()) monkeypatch.setattr(hb, "_session_db", lambda: DB()) @@ -909,16 +949,29 @@ class TestBridge: def peek_session_id(self, key): return "session-delete" if key == session_key else None + class Sessions: + def __init__(self): + self.deleted = [] + + def search_sessions(self, *, sources, window): + assert "pheby" in sources and "pheby_delivery" in sources + from types import SimpleNamespace + return [ + SimpleNamespace(session=SimpleNamespace( + session_id=sid, session_key=session_key, started_at=float(i))) + for i, sid in enumerate(("session-old", "session-delete")) + ] + + def delete(self, session_id, *, media_root): + self.deleted.append(str(session_id)) + return (session_id,) + + def get(self, _session_id): + return None + class DB: - deleted = None - - def _read_all(self, sql, params): - assert "session_key" in sql and params == (session_key, "pheby", "pheby_delivery") - return [{"id": "session-old"}, {"id": "session-delete"}] - - def delete_sessions(self, session_ids): - self.deleted = list(session_ids) - return len(session_ids) + def __init__(self): + self.sessions = Sessions() store, db = Store(), DB() from pheby import hermes_bridge as hb @@ -926,7 +979,7 @@ class TestBridge: monkeypatch.setattr(hb, "_session_db", lambda: db) assert await hb.delete_conversation(cid) is True - assert db.deleted == ["session-old", "session-delete"] + assert db.sessions.deleted == ["session-old", "session-delete"] assert session_key not in store._entries assert store.saved is True assert await server.router.get_name(cid) is None