The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): SessionDB derives its own store's profile for unstamped session rows
Teknium5cc3da682705
diff --git a/hermes_state.py b/hermes_state.pyindex 4b3c8d27422..9e052a5fff5 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -5915,6 +5915,39 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)# Session lifecycle# =========================================================================+ _PROFILE_DIR_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")++ def _own_profile_name(self) -> Optional[str]:+ """The profile that owns THIS store, derived from ``db_path`` alone.++ Every profile-tree ``state.db`` belongs to exactly one profile+ (``<root>/state.db`` → ``default``,+ ``<root>/profiles/<name>/state.db`` → ``<name>``), so the derivation+ is a single match, never a guess — the same contract+ :meth:`backfill_null_session_profiles` and the web listing's+ ``row_profile`` stamp rely on. Path-based (not+ ``get_active_profile_name()``) on purpose: a gateway serving a+ NON-launch profile opens that profile's store directly, and the row+ must be stamped with the store's owner, not the serving process's+ launch profile. Returns ``None`` for stores outside the profile tree+ (explicit ``db_path`` in tests, ad-hoc copies) — those rows keep the+ legacy NULL rather than a fabricated owner.+ """+ try:+ from hermes_constants import get_default_hermes_root++ root = get_default_hermes_root().resolve()+ parent = Path(self.db_path).resolve().parent+ if parent == root:+ return "default"+ if parent.parent == root / "profiles" and self._PROFILE_DIR_RE.match(+ parent.name+ ):+ return parent.name+ except Exception:+ logger.debug("own-profile derivation failed", exc_info=True)+ return None+def _insert_session_row(self,session_id: str,@@ -5929,7 +5962,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)thread_id: str = None,parent_session_id: str = None,cwd: str = None,- profile_name: str = None,+ profile_name: Optional[str] = None,git_repo_root: str = None,origin_json: str = None,display_name: str = None,@@ -5968,7 +6001,23 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)``thread_id``/``display_name``/``origin_json``) are inherited too, so acrash before the gateway re-records the peer can't strand the childwithout a recoverable routing mapping (#59527).- """++ When the caller passes no ``profile_name`` at all, the row is stamped+ with THIS store's own profile (:meth:`_own_profile_name`) instead of+ NULL. Every ``state.db`` belongs to exactly one profile — the same+ single-match contract :meth:`backfill_null_session_profiles` relies+ on — so the stamp is derivation, not a guess. Rows minted NULL after+ that one-shot #94724 backfill ran stayed NULL forever, and+ profile-keyed consumers (desktop sidebar scope matching,+ ``@session:<profile>/<id>`` deep links, the fail-closed owner ladder)+ treat NULL as unowned: the session vanishes from the sidebar even+ though its transcript is intact (#99222). Stores outside the profile+ tree (explicit ``db_path`` in tests, ad-hoc copies) derive nothing+ and keep NULL — never guess.+ """+ if not (profile_name or "").strip():+ profile_name = self._own_profile_name()+def _do(conn):system_prompt_hash = self._store_system_prompt(conn, system_prompt)conn.execute(@@ -6216,9 +6265,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)"""INSERT INTO sessions (id, source, user_id, session_key, chat_id,chat_type, thread_id, display_name, origin_json,- started_at+ profile_name, started_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETsession_key = COALESCE(sessions.session_key, excluded.session_key),chat_id = COALESCE(sessions.chat_id, excluded.chat_id),@@ -6236,6 +6285,11 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)thread_id,display_name,origin_json,+ # Same ownership stamp as _insert_session_row: a+ # self-healed row is a first creation too, and an+ # unowned (NULL) row vanishes from profile-keyed+ # consumers (#99222).+ self._own_profile_name(),time.time(),),)@@ -7137,8 +7191,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)# compression-fork backfill (#59527 / cross-profile jump# fix): the child stays on the parent's profile and keeps# the gateway routing/origin columns so peer recovery- # still works after a crash at the boundary.- profile_name or parent["profile_name"],+ # still works after a crash at the boundary. When neither+ # names an owner (legacy NULL parent), stamp this store's+ # own profile so the rotated child doesn't extend the+ # unowned lineage (#99222).+ profile_name+ or parent["profile_name"]+ or self._own_profile_name(),parent["user_id"],parent["session_key"],parent["chat_id"],diff --git a/tests/test_session_db_profile_stamp.py b/tests/test_session_db_profile_stamp.pynew file mode 100644index 00000000000..af6044b38b5--- /dev/null+++ b/tests/test_session_db_profile_stamp.py@@ -0,0 +1,137 @@+"""SessionDB stamps its own store's profile onto new session rows (#99222).++Every profile-tree ``state.db`` belongs to exactly one profile, so when a+creation path passes no ``profile_name`` the store derives its own owner+instead of persisting NULL. NULL rows minted after the one-shot #94724+legacy-owner backfill stayed NULL forever and vanished from profile-keyed+consumers (desktop sidebar scope matching, ``@session:<profile>/<id>`` deep+links). Stores outside the profile tree must NOT guess — they keep NULL.+"""++import sqlite3++import pytest++import hermes_state+from hermes_state import SessionDB+++def hermes_root(tmp_path, monkeypatch):+ root = tmp_path / "hermes"+ (root / "profiles" / "workprof").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(root))+ # get_default_hermes_root memoizes on (native_home, env) — the env change+ # invalidates the memo by itself, but re-point DEFAULT_DB_PATH so any+ # default-constructed SessionDB in the module under test stays sandboxed.+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", root / "state.db")+ return root+++def _profile_of(db_path, session_id):+ conn = sqlite3.connect(db_path)+ try:+ row = conn.execute(+ "SELECT profile_name FROM sessions WHERE id = ?", (session_id,)+ ).fetchone()+ return row[0] if row else None+ finally:+ conn.close()+++def test_default_store_stamps_default(hermes_root):+ db = SessionDB(db_path=hermes_root / "state.db")+ try:+ db.create_session("s_default", source="cli")+ finally:+ db.close()+ assert _profile_of(hermes_root / "state.db", "s_default") == "default"+++def test_named_profile_store_stamps_own_name(hermes_root):+ db_path = hermes_root / "profiles" / "workprof" / "state.db"+ db = SessionDB(db_path=db_path)+ try:+ db.create_session("s_prof", source="desktop")+ finally:+ db.close()+ assert _profile_of(db_path, "s_prof") == "workprof"+++def test_explicit_profile_name_wins(hermes_root):+ db = SessionDB(db_path=hermes_root / "state.db")+ try:+ db.create_session("s_explicit", source="cli", profile_name="llm-wiki")+ finally:+ db.close()+ assert _profile_of(hermes_root / "state.db", "s_explicit") == "llm-wiki"+++def test_store_outside_profile_tree_never_guesses(hermes_root, tmp_path):+ db_path = tmp_path / "elsewhere" / "state.db"+ db_path.parent.mkdir()+ db = SessionDB(db_path=db_path)+ try:+ db.create_session("s_outside", source="cli")+ finally:+ db.close()+ assert _profile_of(db_path, "s_outside") is None+++def test_compression_child_of_null_parent_is_stamped(hermes_root):+ db_path = hermes_root / "state.db"+ db = SessionDB(db_path=db_path)+ try:+ db.create_session("s_parent", source="cli")+ # Simulate a legacy pre-ownership parent row.+ conn = sqlite3.connect(db_path)+ conn.execute(+ "UPDATE sessions SET profile_name = NULL WHERE id = ?", ("s_parent",)+ )+ conn.commit()+ conn.close()+ db.publish_compression_child(+ parent_session_id="s_parent",+ child_session_id="s_child",+ source="cli",+ messages=[{"role": "user", "content": "hi"}],+ require_compression_lease=False,+ )+ finally:+ db.close()+ assert _profile_of(db_path, "s_child") == "default"+++def test_peer_self_heal_insert_is_stamped(hermes_root):+ db_path = hermes_root / "state.db"+ db = SessionDB(db_path=db_path)+ try:+ # No prior row: the #82616 self-heal INSERT creates it.+ db.record_gateway_session_peer(+ "s_selfheal",+ source="telegram",+ user_id="u1",+ session_key="k1",+ chat_id="c1",+ )+ finally:+ db.close()+ assert _profile_of(db_path, "s_selfheal") == "default"+++def test_legacy_backfill_still_targets_only_null(hermes_root):+ """The one-shot #94724 backfill contract is unchanged: explicit owners are+ never overwritten, and new rows no longer regenerate its input."""+ db_path = hermes_root / "state.db"+ db = SessionDB(db_path=db_path)+ try:+ db.create_session("s_new", source="cli")+ conn = sqlite3.connect(db_path)+ conn.execute("UPDATE sessions SET profile_name = NULL WHERE id = 's_new'")+ conn.commit()+ conn.close()+ assert db.backfill_null_session_profiles("workprof") == 1+ assert db.backfill_null_session_profiles("workprof") == 0+ finally:+ db.close()+ assert _profile_of(db_path, "s_new") == "workprof"