Skip to content

The agent that grows with you

fix(sessions): prune/archive spare pinned sessions by default (data loss)

Teknium76653a8eba15
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 0a19ed30483..33023ae4285 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -13496,6 +13496,11 @@ def main():
action="store_true",
help="Also delete archived sessions (excluded by default)",
)
+ sessions_prune.add_argument(
+ "--include-pinned",
+ action="store_true",
+ help="Also delete pinned sessions (excluded by default — pin is a keep flag)",
+ )
sessions_prune.add_argument(
"--never-active",
action="store_true",
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index da8a2bdda03..e2ef5998d74 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -866,12 +866,21 @@ def cmd_sessions(args, sessions_parser=None):
if not resolved_session_id:
print(f"Session '{args.session_id}' not found.")
return
+ # Note when the explicit target is pinned — the user named this id
+ # directly so we honor the delete, but a pin is a "keep" flag and
+ # silently destroying it (round-3 QA SES-01) is surprising.
+ _get_session = getattr(db, "get_session", None)
+ _meta = (_get_session(resolved_session_id) or {}) if callable(_get_session) else {}
+ _pinned_note = " (this session is PINNED)" if _meta.get("pinned") else ""
if not args.yes:
if not _confirm_prompt(
- f"Delete session '{resolved_session_id}' and all its messages? [y/N] "
+ f"Delete session '{resolved_session_id}'{_pinned_note} "
+ "and all its messages? [y/N] "
):
print("Cancelled.")
return
+ elif _pinned_note:
+ print(f"Warning: deleting a pinned session '{resolved_session_id}'.")
sessions_dir = get_hermes_home() / "sessions"
if db.delete_session(resolved_session_id, sessions_dir=sessions_dir):
print(f"Deleted session '{resolved_session_id}'.")
@@ -941,6 +950,37 @@ def cmd_sessions(args, sessions_parser=None):
else:
filters["archived"] = False
+ # Pinned sessions are excluded by default from bulk prune/archive
+ # (pin = durable keep). `prune --include-pinned` opts in; archive has
+ # no such flag, so archive always spares pinned rows. Surface a count
+ # of pinned matches being skipped so the user knows they were spared.
+ _include_pinned = getattr(args, "include_pinned", False)
+ filters["include_pinned"] = _include_pinned
+ _count_matches = getattr(db, "count_prune_matches", None)
+ if not _include_pinned and callable(_count_matches):
+ _base = {k: v for k, v in filters.items() if k != "include_pinned"}
+ try:
+ _with_pinned = int(_count_matches(**_base, include_pinned=True))
+ _without_pinned = int(_count_matches(**_base, include_pinned=False))
+ _pinned_skipped = max(_with_pinned - _without_pinned, 0)
+ except TypeError:
+ # A db double without include_pinned support — skip the note.
+ _pinned_skipped = 0
+ if _pinned_skipped:
+ _suffix = "" if _pinned_skipped == 1 else "s"
+ _verb_word = "deleted" if action == "prune" else "archived"
+ _optin = (
+ "Pass --include-pinned to delete them anyway, or unpin "
+ "first with `hermes sessions unpin <id>`."
+ if action == "prune"
+ else "Unpin first with `hermes sessions unpin <id>` to include them."
+ )
+ print(
+ f"Note: {_pinned_skipped} pinned session{_suffix} also match "
+ f"these filters but will NOT be {_verb_word} (pin is a keep "
+ f"flag). {_optin}"
+ )
+
candidates = db.list_prune_candidates(**filters)
# Archive expands each selected row to its compression lineage, which
# can include open continuations; a direct-open count would therefore
diff --git a/hermes_state.py b/hermes_state.py
index e5df0c816a1..9fdc820035a 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -11692,6 +11692,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
max_cost: Optional[float] = None,
min_tool_calls: Optional[int] = None,
max_tool_calls: Optional[int] = None,
+ include_pinned: bool = False,
) -> Tuple[str, list]:
"""Build the shared WHERE clause for bulk prune/archive selection.
@@ -11804,6 +11805,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
clauses.append("s.archived = 1")
elif archived is False:
clauses.append("s.archived = 0")
+ # Pinned sessions are a durable "keep" flag (exempt from the stale
+ # auto-archive sweep). Bulk prune/delete/archive must honor that too:
+ # exclude pinned rows unless the caller explicitly opts in. Without
+ # this, `sessions prune`/`delete`/`archive` with a filter silently
+ # destroyed pinned conversations (round-3 QA SES-01, data loss).
+ if not include_pinned:
+ clauses.append("COALESCE(s.pinned, 0) = 0")
return " AND ".join(clauses), params
@staticmethod
@@ -11854,6 +11862,26 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
return [dict(row) for row in cursor.fetchall()]
+ def count_prune_matches(
+ self,
+ older_than_days: Optional[float] = None,
+ source: str = None,
+ **filters,
+ ) -> int:
+ """Count sessions a matching prune/archive would touch.
+
+ Same filter surface as :meth:`list_prune_candidates` (including the
+ ``include_pinned`` tri-state), but returns only a count. Used by the
+ CLI to report how many pinned sessions are being spared.
+ """
+ self._apply_prune_age_filter(older_than_days, filters)
+ where, params = self._prune_filter_where(source=source, **filters)
+ with self._lock:
+ cursor = self._conn.execute(
+ f"SELECT COUNT(*) FROM sessions s WHERE {where}", params
+ )
+ return int(cursor.fetchone()[0])
+
def count_open_prune_matches(
self,
older_than_days: Optional[float] = None,
diff --git a/tests/hermes_cli/test_prune_spares_pinned.py b/tests/hermes_cli/test_prune_spares_pinned.py
new file mode 100644
index 00000000000..db49db73670
--- /dev/null
+++ b/tests/hermes_cli/test_prune_spares_pinned.py
@@ -0,0 +1,80 @@
+"""Regression tests: pinned sessions survive bulk prune/archive (round-3 SES-01).
+
+Pinning is a durable "keep" flag. Before this fix `_prune_filter_where` had no
+pinned exclusion, so `hermes sessions prune`/`archive` with a filter silently
+destroyed pinned conversations. These drive the real SessionDB (temp file DB).
+"""
+
+import time
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ d = SessionDB(tmp_path / "state.db")
+ yield d
+ try:
+ d.close()
+ except Exception:
+ pass
+
+
+def _mk(db, sid, title, pinned=False):
+ db.create_session(sid, source="cli")
+ db.set_session_title(sid, title)
+ # mark ended + old so it is prune-eligible
+ with db._lock:
+ db._conn.execute(
+ "UPDATE sessions SET ended_at=?, started_at=?, message_count=1 WHERE id=?",
+ (time.time() - 100 * 86400, time.time() - 100 * 86400, sid),
+ )
+ db._conn.commit()
+ if pinned:
+ db.set_session_pinned(sid, True)
+
+
+def test_prune_spares_pinned_by_default(db):
+ _mk(db, "20260101_000000_aaaaaa", "keep me", pinned=True)
+ _mk(db, "20260101_000001_bbbbbb", "delete me", pinned=False)
+
+ # Filter matches both by title substring "me"; default must spare pinned.
+ cands = db.list_prune_candidates(title_like="me")
+ ids = {c["id"] for c in cands}
+ assert "20260101_000001_bbbbbb" in ids
+ assert "20260101_000000_aaaaaa" not in ids # pinned excluded
+
+ deleted = db.prune_sessions(older_than_days=None, title_like="me")
+ assert deleted == 1
+ assert db.get_session("20260101_000000_aaaaaa") is not None # pinned survived
+ assert db.get_session("20260101_000001_bbbbbb") is None
+
+
+def test_prune_include_pinned_opts_in(db):
+ _mk(db, "20260101_000000_aaaaaa", "keep me", pinned=True)
+
+ # With the opt-in, the pinned row IS eligible.
+ cands = db.list_prune_candidates(title_like="me", include_pinned=True)
+ assert {c["id"] for c in cands} == {"20260101_000000_aaaaaa"}
+
+ deleted = db.prune_sessions(older_than_days=None, title_like="me", include_pinned=True)
+ assert deleted == 1
+ assert db.get_session("20260101_000000_aaaaaa") is None
+
+
+def test_count_prune_matches_reflects_pinned_flag(db):
+ _mk(db, "20260101_000000_aaaaaa", "keep me", pinned=True)
+ _mk(db, "20260101_000001_bbbbbb", "delete me", pinned=False)
+
+ assert db.count_prune_matches(title_like="me", include_pinned=False) == 1
+ assert db.count_prune_matches(title_like="me", include_pinned=True) == 2
+
+
+def test_archive_spares_pinned(db):
+ _mk(db, "20260101_000000_aaaaaa", "keep me", pinned=True)
+ _mk(db, "20260101_000001_bbbbbb", "arch me", pinned=False)
+
+ archived = db.archive_sessions(older_than_days=None, title_like="me")
+ assert archived == 1 # only the unpinned one