The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): un-hide an auto-archived chat when it is resumed or compressed
Austin Pickett6397a84a9113
diff --git a/hermes_cli/session_schema_history.py b/hermes_cli/session_schema_history.pyindex 09c52e5ea6f..cc8943e9bca 100644--- a/hermes_cli/session_schema_history.py+++ b/hermes_cli/session_schema_history.py@@ -206,6 +206,7 @@ SCHEMA_HISTORY: dict[str, _TableHistory] = {('27 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),('28 2026-09-25T23:25Z 2941aadffa', (('+', 'compression_overload_streak', 'compression_recovery_deadline'),)),('29 2026-09-27T00:29Z d75f29934b', (('+', 'created_source', 'source'),)),+ ('30 2026-09-28T00:00Z #117713', (('+', 'auto_archived', 'archived'),)),),),"messages": _TableHistory(diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 5f8aba68ef4..409a8c458bb 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -417,6 +417,7 @@ CREATE TABLE IF NOT EXISTS sessions (transport_profile TEXT,rewind_count INTEGER NOT NULL DEFAULT 0,archived INTEGER NOT NULL DEFAULT 0,+ auto_archived INTEGER NOT NULL DEFAULT 0,pinned INTEGER NOT NULL DEFAULT 0,hidden INTEGER NOT NULL DEFAULT 0,last_read_at REAL,diff --git a/hermes_state_compression.py b/hermes_state_compression.pyindex aa1be22bb03..d3fcec03c84 100644--- a/hermes_state_compression.py+++ b/hermes_state_compression.py@@ -220,15 +220,19 @@ 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- ) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ thread_id, display_name, origin_json, started_at,+ archived, auto_archived+ ) 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"], 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),)def publish_compression_child(@@ -268,7 +272,8 @@ class SessionCompressionMixin:parent = conn.execute("""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+ thread_id, display_name, origin_json, profile_name, tool_names,+ archived, auto_archivedFROM sessions WHERE id = ?""",(parent_session_id,),).fetchone()@@ -312,6 +317,10 @@ class SessionCompressionMixin:"WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))if updated.rowcount != 1:raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")+ if parent["archived"]:+ # A live continuation under an idle-sweep archive re-activates the chat; after the+ # closure above the child is linked into the lineage walk (#117713).+ self._unarchive_auto_archived_lineage(conn, child_session_id)self._execute_transcript_write(_do, messages)def _write_sql_logged(self, op: str, session_id: str, sql: str, params) -> None:diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 77fde861588..6ec0497489c 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -294,7 +294,8 @@ class SessionMaintenanceMixin:ORDER BY s.started_at ASC""", (self.CANONICAL_BOT_CHAT_TITLE, cutoff))for row in rows:- self.set_session_archived(row[0], True)+ # Sweep provenance: a later compression/resume of this lineage un-hides it (#117713).+ self._auto_archive_lineage(row[0])return len(rows)def prune_sessions(self, older_than_days: Optional[float] = 90, source: str = None,diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 10f684cc25a..cbfb5b954a9 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -42,6 +42,34 @@ def _delegate_from_json(col: str = "model_config") -> str:# ("merged config is empty → store NULL")._MODEL_CONFIG_ROW_MISSING = object()+# ``lineage(id)``: the compression lineage of the session bound twice as ``(?, ?)`` —+# ancestors through compression-ended parents plus compression continuations after it.+_LINEAGE_CTE_SQL = """+ WITH RECURSIVE+ ancestors(id) AS (+ SELECT ?+ UNION+ SELECT parent.id+ FROM ancestors a+ JOIN sessions child ON child.id = a.id+ JOIN sessions parent ON parent.id = child.parent_session_id+ WHERE parent.end_reason = 'compression'+ ),+ descendants(id) AS (+ SELECT ?+ UNION+ SELECT child.id+ FROM descendants d+ JOIN sessions parent ON parent.id = d.id+ JOIN sessions child ON child.parent_session_id = parent.id+ WHERE parent.end_reason = 'compression'+ ),+ lineage(id) AS (+ SELECT id FROM ancestors+ UNION+ SELECT id FROM descendants+ )"""+def _parse_model_config(raw: Any) -> Dict[str, Any]:"""Tolerant ``model_config`` decode: JSON text or dict -> dict copy; anything else -> {}."""@@ -500,6 +528,8 @@ class SessionSessionsMixin:conn.execute("UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?", (session_id,),)+ # Resuming re-activates the chat: drop the idle sweep's archive (never a manual one).+ self._unarchive_auto_archived_lineage(conn, session_id)self._execute_write(_do)def promote_to_session_reset(self, session_id: str, reason: str = "session_reset") -> bool:@@ -864,45 +894,57 @@ class SessionSessionsMixin:(),) or 0)- def _set_lineage_column(self, column: str, session_id: str, value: Any) -> bool:+ def _set_lineage_column(self, column: str, session_id: str, value: Any, *,+ extra_set_sql: str = "") -> bool:"""Set one ``sessions`` column across a whole compression lineage: Desktop projects roots- forward to their tip, so updating only the tip would let the root resurrect it on refresh."""+ forward to their tip, so updating only the tip would let the root resurrect it on refresh.+ *extra_set_sql* (trusted literal, ``, col = expr``) rides the same UPDATE."""return self._write_rowcount(- f"""- WITH RECURSIVE- ancestors(id) AS (- SELECT ?- UNION- SELECT parent.id- FROM ancestors a- JOIN sessions child ON child.id = a.id- JOIN sessions parent ON parent.id = child.parent_session_id- WHERE parent.end_reason = 'compression'- ),- descendants(id) AS (- SELECT ?- UNION- SELECT child.id- FROM descendants d- JOIN sessions parent ON parent.id = d.id- JOIN sessions child ON child.parent_session_id = parent.id- WHERE parent.end_reason = 'compression'- ),- lineage(id) AS (- SELECT id FROM ancestors- UNION- SELECT id FROM descendants- )+ _LINEAGE_CTE_SQL + f"""UPDATE sessions- SET {column} = ?+ SET {column} = ?{extra_set_sql}WHERE id IN (SELECT id FROM lineage)""",(session_id, session_id, value),) > 0def set_session_archived(self, session_id: str, archived: bool) -> bool:- """Soft-hide (or unhide) a session and its compression lineage; messages are kept."""- return self._set_lineage_column("archived", session_id, int(archived))+ """Soft-hide (or unhide) a session and its compression lineage; messages are kept.+ This is the DELIBERATE archive (user, CLI, API): it clears the ``auto_archived``+ provenance, so re-activation never un-hides it on the user's behalf."""+ return self._set_lineage_column(+ "archived", session_id, int(archived), extra_set_sql=", auto_archived = 0")++ def _auto_archive_lineage(self, session_id: str) -> bool:+ """The idle sweep's archive: like :meth:`set_session_archived` but stamps+ ``auto_archived`` on the rows IT hides. A row already archived keeps its provenance, so a+ deliberately archived ancestor is never relabelled as sweep-owned (SQLite evaluates every+ SET expression against the pre-update row)."""+ return self._set_lineage_column(+ "archived", session_id, 1,+ extra_set_sql=", auto_archived = CASE WHEN archived = 0 THEN 1 ELSE auto_archived END")++ @staticmethod+ def _unarchive_auto_archived_lineage(conn, session_id: str) -> bool:+ """Un-hide a lineage the idle sweep archived, on *conn* (caller's write txn). A tip that is+ published (compression) or reopened (resume) under it is live again, and the listing admits+ a lineage by its ROOT's flag, so leaving the sweep's stamp would hide an active chat (#117713).+ A lineage with ANY deliberately archived row (``archived = 1 AND auto_archived = 0``) is left+ alone: a manual archive stays until the user un-archives it. True when rows were un-hidden."""+ params = (session_id, session_id)+ manual = conn.execute(+ _LINEAGE_CTE_SQL + """+ SELECT 1 FROM sessions+ WHERE id IN (SELECT id FROM lineage) AND archived <> 0 AND COALESCE(auto_archived, 0) = 0+ LIMIT 1+ """, params).fetchone()+ if manual is not None:+ return False+ return conn.execute(+ _LINEAGE_CTE_SQL + """+ UPDATE sessions SET archived = 0, auto_archived = 0+ WHERE id IN (SELECT id FROM lineage) AND archived <> 0+ """, params).rowcount > 0# Accidental end reasons recovery treats as resumable (also interpolated into# the recovery/promotion SQL so literals cannot drift).diff --git a/tests/hermes_state/test_auto_archived_lineage_reactivation.py b/tests/hermes_state/test_auto_archived_lineage_reactivation.pynew file mode 100644index 00000000000..7e1475ea4db--- /dev/null+++ b/tests/hermes_state/test_auto_archived_lineage_reactivation.py@@ -0,0 +1,133 @@+"""A chat the idle sweep archived must reappear once it is live again (#117713).++The sidebar admits a compression lineage by its ROOT's ``archived`` flag. When+``sessions.auto_archive`` hid an idle lineage and the chat later resumed and+compressed, the fresh tip was inserted with ``archived=0`` under the archived+root, so the live chat stayed invisible. A DELIBERATE archive (user/API/CLI)+must keep hiding the chat through the same re-activation.+"""+import time++import pytest++from hermes_state import SessionDB+++def db(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ return SessionDB(tmp_path / "state.db")+++def _sidebar_ids(db):+ """Same flags as the desktop sidebar slice (tips projected from roots)."""+ return {+ row["id"]+ for row in db.list_sessions_rich(+ limit=50, offset=0, min_message_count=1, include_archived=False,+ archived_only=False, order_by_last_active=True, compact_rows=True, include_pinned=True,+ )+ }+++def _compress(db, parent, child):+ holder = f"holder-{child}"+ assert db.try_acquire_compression_lock(parent, holder, ttl_seconds=60)+ db.publish_compression_child(+ parent_session_id=parent, child_session_id=child, source="telegram", system_prompt="p",+ messages=[{"role": "user", "content": f"summary for {child}"}], compression_lock_holder=holder)+++def _flags(db, *ids):+ return {sid: (db.get_session(sid)["archived"], db.get_session(sid)["auto_archived"]) for sid in ids}+++def _lineage(db):+ """root -> mid (compression) -> tip, all with messages."""+ db.create_session("root", "telegram")+ db.append_message("root", "user", "hello")+ _compress(db, "root", "mid")+ _compress(db, "mid", "tip")+ db.append_message("tip", "user", "latest")+++def _sweep(db):+ time.sleep(0.02)+ return db.archive_stale_sessions(0)+++def test_compression_after_auto_archive_unhides_the_live_chat(db):+ _lineage(db)+ assert _sweep(db) == 1+ assert _flags(db, "root", "mid", "tip") == {s: (1, 1) for s in ("root", "mid", "tip")}+ assert not _sidebar_ids(db)++ # A new inbound message resumes the chat and compression publishes a fresh tip.+ _compress(db, "tip", "tip2")++ assert _flags(db, "root", "mid", "tip", "tip2") == {+ s: (0, 0) for s in ("root", "mid", "tip", "tip2")}+ assert _sidebar_ids(db) == {"tip2"}+++def test_compression_keeps_a_manually_archived_chat_hidden(db):+ _lineage(db)+ assert db.set_session_archived("tip", True)++ _compress(db, "tip", "tip2")++ # The new tip inherits the deliberate archive instead of creating a mixed lineage.+ assert _flags(db, "root", "mid", "tip", "tip2") == {+ s: (1, 0) for s in ("root", "mid", "tip", "tip2")}+ assert not _sidebar_ids(db)+ # ...so a later idle sweep has no archived=0 tip to relabel as sweep-owned.+ assert _sweep(db) == 0+ _compress(db, "tip2", "tip3")+ assert not _sidebar_ids(db)+++def test_manual_archive_overrides_sweep_provenance(db):+ _lineage(db)+ assert _sweep(db) == 1+ assert db.set_session_archived("root", True) # user archives it deliberately afterwards+ assert _flags(db, "root", "mid", "tip") == {s: (1, 0) for s in ("root", "mid", "tip")}++ _compress(db, "tip", "tip2")+ assert not _sidebar_ids(db)+++def test_sweep_does_not_relabel_a_manually_archived_ancestor(db):+ """Legacy mixed lineage (pre-fix): manually archived root, unarchived continuation tip."""+ _lineage(db)+ db._write_sql("UPDATE sessions SET archived = 1 WHERE id IN ('root', 'mid')", ())+ assert _sweep(db) == 1 # the tip is still archived=0, so it is a sweep candidate+ assert _flags(db, "root", "mid", "tip") == {"root": (1, 0), "mid": (1, 0), "tip": (1, 1)}++ _compress(db, "tip", "tip2")+ assert not _sidebar_ids(db)+ assert db.get_session("root")["archived"] == 1+++def test_resume_reopen_unhides_auto_archived_but_not_manual(db):+ db.create_session("auto", "cli")+ db.append_message("auto", "user", "a")+ db.end_session("auto", "cli_close")+ db.create_session("manual", "cli")+ db.append_message("manual", "user", "m")+ db.end_session("manual", "cli_close")+ assert db.set_session_archived("manual", True)+ assert _sweep(db) == 1+ assert _flags(db, "auto", "manual") == {"auto": (1, 1), "manual": (1, 0)}++ db.reopen_session("auto")+ db.reopen_session("manual")++ assert _flags(db, "auto", "manual") == {"auto": (0, 0), "manual": (1, 0)}+ assert _sidebar_ids(db) == {"auto"}+++def test_unarchive_clears_sweep_provenance(db):+ _lineage(db)+ assert _sweep(db) == 1+ assert db.set_session_archived("tip", False)+ assert _flags(db, "root", "mid", "tip") == {s: (0, 0) for s in ("root", "mid", "tip")}diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex 1bacf56e8f5..ff6206f97ed 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -152,7 +152,9 @@ Abridged — see `SCHEMA_SQL` in `hermes_state_common.py` (applied by `hermes_st`chat_type`, `thread_id`, `display_name`, `origin_json`, `expiry_finalized`,workspace fields `cwd` / `git_branch` / `git_repo_root`, handoff andcompression-failure fields, `profile_name`, `transport_profile` (the multiplex-bot that received the lane, nullable), `rewind_count`, `archived`, and+bot that received the lane, nullable), `rewind_count`, `archived`,+`auto_archived` (set only by the idle sweep; a resume or compression+continuation clears a sweep-only archive, never a deliberate one), and`pinned`):```sqldiff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex e8c6756279a..8ad285e0003 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -600,6 +600,11 @@ Archived sessions are hidden from`hermes sessions list` and `/resume` but remain in the database and can beunarchived from the Desktop/Dashboard session list.+A chat hidden by the `sessions.auto_archive` idle sweep comes back on its own+once it is live again — when it is resumed, or when new activity compresses it+into a fresh continuation. A chat you archived yourself (sidebar, API, or+`hermes sessions archive`) stays archived until you unarchive it.+### Session Statistics```bash