The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): a pin covers the segments compression publishes after it
John Paul Soliva247b6a16407d
diff --git a/hermes_state_compression.py b/hermes_state_compression.pyindex b1de55cb92e..ce6679b2e8d 100644--- a/hermes_state_compression.py+++ b/hermes_state_compression.py@@ -226,16 +226,18 @@ class SessionCompressionMixin:system_prompt_hash, tool_names,parent_session_id, cwd, git_branch, git_repo_root,profile_name, user_id, session_key, chat_id, chat_type,- thread_id, display_name, origin_json, started_at,+ thread_id, display_name, origin_json, pinned, started_at,archived, auto_archived- ) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ ) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(child_session_id, source, model, json.dumps(model_config) if model_config else None,system_prompt_hash, parent["tool_names"], parent_session_id, cwd or parent["cwd"], parent["git_branch"],parent["git_repo_root"],profile_name or parent["profile_name"] or self._own_profile_name(),parent["user_id"], parent["session_key"], parent["chat_id"], parent["chat_type"],- parent["thread_id"], parent["display_name"], parent["origin_json"], time.time(),+ parent["thread_id"], parent["display_name"], parent["origin_json"],+ # The pin is lineage-wide (set_session_pinned); a segment published after it joins it.+ int(parent["pinned"] or 0), time.time(),# Inherit the lineage's archive state so a manually archived chat stays uniformly# archived (a mixed lineage let the sweep re-stamp its fresh tip as auto-archived).parent["archived"] or 0, parent["auto_archived"] or 0),@@ -279,7 +281,7 @@ class SessionCompressionMixin:"""SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,user_id, session_key, chat_id, chat_type,thread_id, display_name, origin_json, profile_name, tool_names,- archived, auto_archived+ archived, auto_archived, pinnedFROM sessions WHERE id = ?""",(parent_session_id,),).fetchone()diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 6ec0497489c..ac2818e3ec6 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -91,6 +91,18 @@ def _continued_ancestors_sql(candidates_where: str) -> str:") SELECT id FROM kept")+# A pin covers the whole conversation, but a store can hold a pinned segment whose later+# continuations were published unpinned; those still belong to the pinned chat.+_PINNED_TAIL_SQL = ("WITH RECURSIVE tail(id) AS ("+ " SELECT c.id FROM sessions c JOIN sessions p ON p.id = c.parent_session_id"+ f" WHERE COALESCE(p.pinned, 0) = 1 AND {_CONTINUATION_EDGE_SQL}"+ " UNION"+ " SELECT c.id FROM tail t JOIN sessions p ON p.id = t.id JOIN sessions c ON c.parent_session_id = p.id"+ f" WHERE {_CONTINUATION_EDGE_SQL}"+ ") SELECT id FROM tail")+_NOT_PINNED_SQL = f"COALESCE(s.pinned, 0) = 0 AND s.id NOT IN ({_PINNED_TAIL_SQL})"++class SessionMaintenanceMixin:"""Retention pruning, stale-session archiving and VACUUM policy for SessionDB."""@@ -222,7 +234,7 @@ class SessionMaintenanceMixin:clauses.append(f"s.archived = {int(archived)}")# Pinned is a durable "keep" flag: bulk prune/delete/archive exclude pinned rows unless opted in.if not include_pinned:- clauses.append("COALESCE(s.pinned, 0) = 0")+ clauses.append(_NOT_PINNED_SQL)return " AND ".join(clauses), paramsdef _prune_where(self, older_than_days, source, filters, *, whole_lineages: bool = False) -> Tuple[str, list]:@@ -282,7 +294,7 @@ class SessionMaintenanceMixin:if idle_days is None or idle_days < 0:return 0cutoff = time.time() - float(idle_days) * 86400.0- pin_clause = "AND s.pinned = 0" if exclude_pinned else ""+ pin_clause = f"AND {_NOT_PINNED_SQL}" if exclude_pinned else ""rows = self._read_all(f"""SELECT s.id FROM sessions sdiff --git a/tests/hermes_state/test_pinned_lineage.py b/tests/hermes_state/test_pinned_lineage.pynew file mode 100644index 00000000000..3127e6887a6--- /dev/null+++ b/tests/hermes_state/test_pinned_lineage.py@@ -0,0 +1,42 @@+"""A pin covers the whole conversation, including segments compression publishes after it."""+import time+from contextlib import closing++from hermes_state import SessionDB+++def _pinned_then_rotated(db):+ """Chat ``keep`` is pinned, then rotates to ``keep-2``; both idle for 120 days."""+ old = time.time() - 120 * 86400+ db.create_session("keep", source="cli")+ db.append_message("keep", "user", "early detail", timestamp=old)+ assert db.set_session_pinned("keep", True)+ db.publish_compression_child(parent_session_id="keep", child_session_id="keep-2", source="cli",+ messages=[{"role": "user", "content": "[summary]", "timestamp": old + 60}],+ require_compression_lease=False)+ db.end_session("keep-2", "done")+ db._conn.execute("UPDATE sessions SET started_at = ?, ended_at = ? WHERE id IN ('keep', 'keep-2')",+ (old, old + 120))+ db._conn.commit()+++def test_a_pin_follows_the_chat_through_compression(tmp_path):+ with closing(SessionDB(tmp_path / "state.db")) as db:+ _pinned_then_rotated(db)++ assert db.get_session("keep-2")["pinned"] == db.get_session("keep")["pinned"] == 1+++def test_bulk_cleanup_spares_a_chat_pinned_before_it_rotated(tmp_path):+ """Stores written before the pin followed rotation hold a pinned segment with an unpinned tip."""+ with closing(SessionDB(tmp_path / "state.db")) as db:+ _pinned_then_rotated(db)+ db._conn.execute("UPDATE sessions SET pinned = 0 WHERE id = 'keep-2'")+ db._conn.commit()++ assert db.list_prune_candidates(older_than_days=90, whole_lineages=True) == []+ assert db.prune_sessions(older_than_days=90) == 0+ assert db.archive_stale_sessions(3) == db.archive_sessions(older_than_days=90) == 0+ assert db.get_compression_lineage("keep") == ["keep", "keep-2"]+ assert not db.get_session("keep")["archived"]+ assert db.prune_sessions(older_than_days=90, include_pinned=True) == 2