The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): prune keeps the compressed-away start of a chat still in use
John Paul Soliva7d49b46e15e8
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex fb1e4e3f337..87f80a3a47c 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -679,6 +679,8 @@ def _cmd_prune_or_archive(db, args, action):# Archive flips a compression lineage as a unit, matched through its tip (an old ancestor alone# never qualifies); the preview must show the same rows the archive will touch.filters["lineage_tips_only"] = not prune+ # Prune deletes a compression lineage only as a unit; the preview must list the rows it deletes.+ filters["whole_lineages"] = pruneif not filters["include_pinned"]:_note_pinned_skipped(db, filters, action)candidates = db.list_prune_candidates(**filters)diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex 4fb2b68445d..3daebb7d38e 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -92,7 +92,7 @@ def _prune_sessions(body: SessionPrune):filters = {"older_than_days": effective_older_than, "started_before": body.started_before,"started_after": body.started_after,- "archived": None if body.include_archived else False,+ "archived": None if body.include_archived else False, "whole_lineages": True,**{f: (getattr(body, f) or None) for f in _PRUNE_STR_FILTERS},**{f: getattr(body, f) for f in _PRUNE_NUM_FILTERS}}skipped_open = db.count_open_prune_matches(**filters)diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex a87b6f54600..26a9b642bcc 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -8,7 +8,8 @@ from pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuplefrom hermes_state_common import (- AUTO_VACUUM_MIN_FREELIST_RATIO, _id_chunks, _placeholders, _sql_session_last_active, escape_like as _escape_like+ AUTO_VACUUM_MIN_FREELIST_RATIO, _id_chunks, _placeholders, _sql_json_extract, _sql_session_last_active,+ escape_like as _escape_like)from hermes_startup_watchdog import report_startup_progress@@ -74,6 +75,27 @@ _PRUNE_FILTERS = ()_PRUNE_FILTER_NAMES = frozenset(name for name, _, _ in _PRUNE_FILTERS) | {"archived", "include_pinned", "lineage_tips_only"}+# Child ``c`` continues compression-ended ``p``; a fork names ``p`` in its marker (compression copies+# ``model_config``, so a marker naming another row is inherited, not a fork of ``p``).+_CONTINUATION_EDGE_SQL = " AND ".join([+ "p.end_reason = 'compression'",+ *(f"COALESCE({_sql_json_extract('c.model_config', f'$.{marker}')}, '') != p.id"+ for marker in ("_branched_from", "_delegate_from", "_reset_from")),+ "COALESCE(c.source, '') != 'tool'",+])+++def _continued_ancestors_sql(candidates_where: str) -> str:+ """Compression ancestors of every row *candidates_where* (alias ``s``) does not select."""+ return ("WITH RECURSIVE kept(id) AS ("+ " SELECT p.id FROM sessions c JOIN sessions p ON p.id = c.parent_session_id"+ f" WHERE {_CONTINUATION_EDGE_SQL}"+ f" AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.id = c.id AND {candidates_where})"+ " UNION"+ " SELECT p.id FROM kept k JOIN sessions c ON c.id = k.id JOIN sessions p ON p.id = c.parent_session_id"+ f" WHERE {_CONTINUATION_EDGE_SQL}"+ ") SELECT id FROM kept")+class SessionMaintenanceMixin:"""Retention pruning, stale-session archiving and VACUUM policy for SessionDB."""@@ -205,7 +227,10 @@ class SessionMaintenanceMixin:return " AND ".join(clauses), paramsdef _prune_where(self, older_than_days, source, filters) -> Tuple[str, list]:- """Translate the legacy age window into the shared activity filter, then build WHERE."""+ """Translate the legacy age window into the shared activity filter, then build WHERE.+ ``whole_lineages`` (prune) keeps a compression ancestor while any continuation after it+ is unmatched."""+ whole_lineages = filters.pop("whole_lineages", False)if (older_than_days is not None and filters.get("last_active_before") is Noneand filters.get("started_before") is None):if older_than_days < 0:@@ -213,7 +238,12 @@ class SessionMaintenanceMixin:f"older_than_days must be >= 0, got {older_than_days!r}: a negative ""retention builds a future cutoff that matches every ended session.")filters["last_active_before"] = time.time() - (older_than_days * 86400)- return self._prune_filter_where(source=source, **filters)+ where, params = self._prune_filter_where(source=source, **filters)+ if not whole_lineages:+ return where, params+ # A compressed-away segment ages with its conversation, not on its own: while any later+ # segment stays, deleting it would cut the start off a chat that is still in use.+ return f"{where} AND s.id NOT IN ({_continued_ancestors_sql(where)})", [*params, *params]def list_prune_candidates(self, older_than_days: Optional[float] = None, source: str = None,**filters) -> List[Dict[str, Any]]:@@ -277,7 +307,9 @@ class SessionMaintenanceMixin:Children outside the window are orphaned (parent NULLed), not cascade-deleted. With*sessions_dir*, transcript files are removed outside the DB transaction.``exclude_active_write_guards`` (automatic maintenance) skips rows under a live turn lease- or compression lock while expired/dead holders are reclaimed and fenced."""+ or compression lock while expired/dead holders are reclaimed and fenced. A compression+ ancestor is deleted only together with every continuation after it (``whole_lineages``)."""+ filters["whole_lineages"] = Truewhere, where_params = self._prune_where(older_than_days, source, filters)removed_ids: list[str] = []def _do(conn):diff --git a/tests/hermes_state/test_prune_activity_recency.py b/tests/hermes_state/test_prune_activity_recency.pyindex ad96160ec6f..2e8fb911bda 100644--- a/tests/hermes_state/test_prune_activity_recency.py+++ b/tests/hermes_state/test_prune_activity_recency.py@@ -45,3 +45,36 @@ def test_prune_sessions_respects_touch_session_activity(tmp_path):assert pruned == 1assert db.get_session("truly_old") is Noneassert db.get_session("active_by_heartbeat") is not None+++def test_prune_keeps_the_compressed_segments_of_a_chat_still_in_use(tmp_path):+ """A rotated conversation ages as one: its old compressed-away segments stay while a later segment+ is still in use, and go together once the whole chat is idle. The CLI/dashboard preview lists what prune deletes."""+ with closing(SessionDB(tmp_path / "state.db")) as db:+ old = time.time() - 120 * 86400++ def rotate(parent, child, at):+ db.publish_compression_child(parent_session_id=parent, child_session_id=child, source="cli",+ messages=[{"role": "user", "content": "[summary]", "timestamp": at}],+ require_compression_lease=False)+ db._conn.execute("UPDATE sessions SET ended_at = ? WHERE id = ?", (at, parent))+ db._conn.execute("UPDATE sessions SET started_at = ? WHERE id = ?", (at, child))+ db._conn.commit()++ for chat in ("live", "idle"):+ db.create_session(chat, source="cli")+ db.append_message(chat, "user", f"{chat} early detail", timestamp=old)+ db._conn.execute("UPDATE sessions SET started_at = ? WHERE id = ?", (old, chat))+ db._conn.commit()+ rotate(chat, f"{chat}-2", old + 60)+ rotate(f"{chat}-2", f"{chat}-3", old + 120)+ db.append_message("live-3", "user", "still talking today")+ db.end_session("idle-3", "done")+ db._conn.execute("UPDATE sessions SET ended_at = ? WHERE id = 'idle-3'", (old + 180,))+ db._conn.commit()++ idle = {"idle", "idle-2", "idle-3"}+ assert {c["id"] for c in db.list_prune_candidates(older_than_days=90, whole_lineages=True)} == idle+ assert db.prune_sessions(older_than_days=90) == len(idle)+ assert db.get_compression_lineage("live-3") == ["live", "live-2", "live-3"]+ assert not any(db.get_session(sid) for sid in idle)diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 9387cc88810..582c2b184d4 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -571,6 +571,7 @@ delete them too.:::infoPruning only deletes **ended** sessions (sessions that have been explicitly ended or auto-reset). Active sessions are never pruned.+A conversation that compression split into several sessions is pruned as a unit: its older segments stay while any later segment does.:::### Bulk-Archive Sessions@@ -1077,7 +1078,9 @@ Only **ended** sessions are ever deleted. Active sessions are never auto-pruned,regardless of age. Ended sessions are aged from their last activity — thefreshest of live activity, latest message, or session start — so a long-livedconversation used recently is not deleted merely because it began before the-retention window.+retention window. The same holds for a conversation that compression split into+several sessions: its older segments are kept while any later segment is, and+are pruned together with it once the whole conversation qualifies.**Stale open sessions from automation.** Some producers — cron jobs, kanbanworkers, subagents, one-shot CLI runs — can die without ever marking theirdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.mdindex 07c4e9eed32..208987be459 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/sessions.md@@ -414,6 +414,7 @@ hermes sessions prune --older-than 30 --yes:::info清理仅删除**已结束**的 session(已被显式结束或自动重置的 session)。活跃 session 永远不会被清理。+被压缩拆分成多个 session 的对话作为一个整体清理:只要后续任一段仍保留,较早的段就会保留。:::### Session 统计@@ -591,7 +592,7 @@ sessions:min_interval_hours: 24 # 清理间隔不短于此值```-活跃 session 永远不会被自动清理,无论时间多长。+活跃 session 永远不会被自动清理,无论时间多长。被压缩拆分成多个 session 的对话同样如此:只要后续任一段仍保留,其较早的段就会保留,并在整个对话符合条件后一起清理。### 手动清理