Skip to content

The agent that grows with you

fix(bot-mode): review follow-ups for recoverable-archive resurrection

kshitij4865194772e6
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index bce42f23b59..a9bdea8efec 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -4258,6 +4258,31 @@ class APIServerAdapter(BasePlatformAdapter):
)
if title_filter:
sessions = [s for s in sessions if (s.get("title") or "").strip() == title_filter]
+ if not sessions:
+ # Recoverable-archive resurrection (#92687): a canonical Bot
+ # Chat archived by the ws-orphan reaper / older agent cleanup
+ # is invisible to list_sessions_rich (include_archived=False),
+ # which would fail `hermes peer dm` resolution and mint
+ # transient sessions — same accident the tui_gateway lookups
+ # heal. Resurrect and re-list; deliberate archives stay put.
+ try:
+ from tools.bot_mode_probe import BOT_CHAT_TITLE
+
+ stale = db.get_session_by_title(title_filter) if title_filter == BOT_CHAT_TITLE else None
+ if stale and stale.get("archived") and db.unarchive_recoverable_session(stale["id"]):
+ sessions = await asyncio.to_thread(db.list_sessions_rich,
+ source=source,
+ limit=limit,
+ offset=offset,
+ include_children=include_children,
+ order_by_last_active=True,
+ include_pinned=True,
+ search_query=title_filter,
+ include_hidden=include_hidden,
+ )
+ sessions = [s for s in sessions if (s.get("title") or "").strip() == title_filter]
+ except Exception:
+ pass # resolution degrades to today's no-row behavior
# Back-filled pins arrive PAST the limit, so counting them would report
# another page that doesn't exist. Only the recency window decides.
windowed = sum(1 for s in sessions if not s.get("pinned"))
diff --git a/hermes_state.py b/hermes_state.py
index 0a019a0dc49..d24b695b0ea 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -65,6 +65,8 @@ from hermes_state_common import ( # noqa: F401 (re-exported for back-compat)
_LISTABLE_CHILD_SQL,
_PREVIEW_ELIGIBLE_SQL,
_PREVIEW_RAW_SELECT,
+ _RECOVERABLE_END_REASONS,
+ _RECOVERABLE_END_REASONS_SQL,
_RESET_END_REASONS,
_RESET_END_REASONS_SQL,
_ephemeral_child_sql,
@@ -5747,7 +5749,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash
WHERE s.session_key = ?
AND s.source = ?
- AND (s.ended_at IS NULL OR s.end_reason IN ('agent_close', 'ws_orphan_reap'))
+ AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND NOT EXISTS (
SELECT 1 FROM sessions b
WHERE b.session_key = s.session_key
@@ -5786,7 +5788,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
AND COALESCE(s.chat_id, '') = COALESCE(?, '')
AND COALESCE(s.chat_type, '') = COALESCE(?, '')
AND COALESCE(s.thread_id, '') = COALESCE(?, '')
- AND (s.ended_at IS NULL OR s.end_reason IN ('agent_close', 'ws_orphan_reap'))
+ AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND (COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
))
@@ -6422,7 +6424,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
cursor = conn.execute(
"UPDATE sessions SET ended_at = ?, end_reason = ? "
"WHERE id = ? AND (ended_at IS NULL "
- "OR end_reason IN ('agent_close', 'ws_orphan_reap'))",
+ f"OR end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))",
(now, reason, session_id),
)
return cursor.rowcount
@@ -8829,11 +8831,12 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
rowcount = self._execute_write(_do)
return rowcount > 0
- # Accidental end reasons that recovery treats as resumable (see
- # find_latest_gateway_session_for_peer and promote_to_session_reset,
- # whose SQL literals must stay in sync with this tuple, and
- # docs/session-lifecycle.md "recoverable accidental reasons").
- RECOVERABLE_END_REASONS = ("agent_close", "ws_orphan_reap")
+ # Accidental end reasons that recovery treats as resumable. Single source
+ # of truth: hermes_state_common._RECOVERABLE_END_REASONS, interpolated
+ # into find_latest_gateway_session_for_peer / promote_to_session_reset
+ # SQL — literals cannot drift (docs/session-lifecycle.md "recoverable
+ # accidental reasons").
+ RECOVERABLE_END_REASONS = _RECOVERABLE_END_REASONS
def unarchive_recoverable_session(self, session_id: str) -> bool:
"""Un-archive a session that was archived by a recoverable accident.
@@ -8856,9 +8859,34 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return False
if not row or not row.get("archived"):
return False
- if (row.get("end_reason") or "") not in self.RECOVERABLE_END_REASONS:
+ # A compressed lineage's registry row keeps end_reason='compression';
+ # the accidental stamp lives on the live TIP. Judge recoverability at
+ # the tip (== the row itself when uncompressed).
+ tip = row
+ try:
+ tip_id = self.resolve_resume_session_id(session_id) or session_id
+ if tip_id != session_id:
+ tip = self.get_session(tip_id) or row
+ except Exception:
+ tip_id = session_id
+ if (tip.get("end_reason") or "") not in self.RECOVERABLE_END_REASONS:
+ return False
+ if not self.set_session_archived(session_id, False):
return False
- return self.set_session_archived(session_id, False)
+
+ # Clear the accidental end stamp: the session is live again, and a
+ # surviving ws_orphan_reap/agent_close reason would make a LATER
+ # deliberate archive (which never writes end_reason) auto-resurrect
+ # on the next lookup — permanently overriding user intent.
+ def _clear_end(conn):
+ conn.execute(
+ "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?",
+ (tip["id"],),
+ )
+ return 1
+
+ self._execute_write(_clear_end)
+ return True
def set_session_pinned(self, session_id: str, pinned: bool) -> bool:
"""Pin or unpin a session (and its whole compression lineage).
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 2bc6572810d..e1045f75b3c 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -200,6 +200,13 @@ _RESET_END_REASONS = (
)
_RESET_END_REASONS_SQL = ", ".join(f"'{reason}'" for reason in _RESET_END_REASONS)
+# Accidental end reasons that recovery treats as resumable (see
+# docs/session-lifecycle.md "recoverable accidental reasons"). Interpolated
+# into the recovery SQL below AND exposed as SessionDB.RECOVERABLE_END_REASONS
+# so the tuple is the single source of truth — literals cannot drift.
+_RECOVERABLE_END_REASONS = ("agent_close", "ws_orphan_reap")
+_RECOVERABLE_END_REASONS_SQL = ", ".join(f"'{reason}'" for reason in _RECOVERABLE_END_REASONS)
+
def _legacy_reset_child_sql(alias: str, reasons_sql: str) -> str:
"""Pre-marker reset-continuation heuristic.
diff --git a/tests/tui_gateway/test_profiles_list_canonical_session.py b/tests/tui_gateway/test_profiles_list_canonical_session.py
index abc53a6104b..4f5249ab3e3 100644
--- a/tests/tui_gateway/test_profiles_list_canonical_session.py
+++ b/tests/tui_gateway/test_profiles_list_canonical_session.py
@@ -183,10 +183,44 @@ def test_canonical_session_archived_by_recoverable_reason_is_resurrected(home, r
assert canonical["id"] == "reaped1"
assert "surviving forever chat" in canonical["preview"]
- # The archive flag was durably cleared, not just masked for this call.
+ # Idempotence: a second listing resolves the same row again (the stale
+ # end stamp was cleared, nothing re-hides or re-resurrects in a loop).
+ again = _row(_profiles({}), "default")["canonical_session"]
+ assert again is not None and again["id"] == "reaped1"
+
+ # The archive flag was durably cleared, not just masked for this call —
+ # and the accidental end stamp went with it.
db = _db(home)
try:
- assert not db.get_session("reaped1")["archived"]
+ fresh = db.get_session("reaped1")
+ assert not fresh["archived"]
+ assert fresh["end_reason"] is None
+ finally:
+ db.close()
+
+
+def test_resurrection_unarchives_the_whole_compression_lineage(home):
+ # unarchive_recoverable_session promises lineage-wide un-archive via
+ # set_session_archived: a compressed canonical chat (root + tip both
+ # archived by the reaper) must fully resurrect, resolved to the tip.
+ db = _db(home)
+ _add_session(db, "root1", title="Bot Chat", ts=1000,
+ text="pre-compression", hidden=True,
+ end_reason="compression", archived=True)
+ _add_session(db, "tip1", ts=2000, text="post-compression content",
+ parent="root1", end_reason="ws_orphan_reap", archived=True)
+ db.close()
+
+ row = _row(_profiles({}), "default")
+ canonical = row["canonical_session"]
+ assert canonical is not None
+ assert canonical["id"] == "root1"
+ assert canonical["resolved_id"] == "tip1"
+
+ db = _db(home)
+ try:
+ assert not db.get_session("root1")["archived"]
+ assert not db.get_session("tip1")["archived"]
finally:
db.close()
@@ -270,6 +304,32 @@ def test_session_list_title_lookup_keeps_deliberate_archive_hidden(home, monkeyp
db.close()
+def test_deliberate_archive_after_resurrection_stays_archived(home):
+ # Resurrection must clear the accidental end stamp: if ws_orphan_reap
+ # survived on the row, a LATER deliberate archive (which writes no
+ # end_reason) would auto-resurrect on the next lookup — permanently
+ # overriding user intent.
+ db = _db(home)
+ _add_session(db, "cycle1", title="Bot Chat", ts=1000,
+ text="reaped then retired", hidden=True,
+ end_reason="ws_orphan_reap", archived=True)
+ db.close()
+
+ # First lookup resurrects (accidental archive).
+ row = _row(_profiles({}), "default")
+ assert row["canonical_session"] is not None
+
+ # User now deliberately archives the resurrected row.
+ db = _db(home)
+ assert db.get_session("cycle1")["end_reason"] is None # stamp cleared
+ db.set_session_archived("cycle1", True)
+ db.close()
+
+ # Second lookup must respect the deliberate archive.
+ row = _row(_profiles({}), "default")
+ assert row["canonical_session"] is None
+
+
# ---------------------------------------------------------------------------
# Contract guards
# ---------------------------------------------------------------------------
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 345c65d0579..8f61ba637d2 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -192,16 +192,22 @@ def _(rid, params: dict) -> dict:
title_lookup = str(params.get("title") or "").strip()
if title_lookup:
row = db.get_session_by_title(title_lookup)
- if row and row.get("archived") and title_lookup == "Bot Chat":
- # The canonical Bot Chat is identity-scoped: an archive
- # stamped by the ws-orphan reaper or older agent cleanup
- # (ws_orphan_reap / agent_close) is an accident, not user
- # intent, and hiding the row here makes the desktop mint
- # transient replacements forever (#92687). Resurrect it —
- # same recoverable-reason set as stale-route recovery.
- # Deliberate archives (no/explicit end_reason) still hide.
- if db.unarchive_recoverable_session(row["id"]):
- row = db.get_session_by_title(title_lookup)
+ if row and row.get("archived"):
+ from tools.bot_mode_probe import BOT_CHAT_TITLE
+
+ if title_lookup == BOT_CHAT_TITLE:
+ # The canonical Bot Chat is identity-scoped: an archive
+ # stamped by the ws-orphan reaper or older agent cleanup
+ # (ws_orphan_reap / agent_close) is an accident, not user
+ # intent, and hiding the row here makes the desktop mint
+ # transient replacements forever (#92687). Resurrect it —
+ # same recoverable-reason set as stale-route recovery.
+ # Deliberate archives (no/explicit end_reason) still hide.
+ # Re-fetch by ID: title has no DB-level UNIQUE, so a
+ # title re-query could grab a different (still-archived)
+ # duplicate row.
+ if db.unarchive_recoverable_session(row["id"]):
+ row = db.get_session(row["id"])
if (
not row
or row.get("archived")