Skip to content

The agent that grows with you

fix(cli): a session with a pending first admission is not an empty launch stub

kshitijk4poor9077473ee0d1
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.py
index 1a4aa945f28..b866ed184d2 100644
--- a/gateway/session_local_title.py
+++ b/gateway/session_local_title.py
@@ -49,9 +49,10 @@ def resolve_latest_session(authority, actor, family, workspace=None):
sources = [*families[family], 'local']
for scope in ([workspace] if workspace else []) + [None]:
# A launch stub (the CLI crashed or a resume failed before the first turn) is the newest row
- # and carries the surface from its insert. It has no messages, so it is never "latest".
+ # and carries the surface from its insert. It has no messages and no admission, so it is never
+ # "latest"; a session whose first prompt is admitted but not yet written still is.
for row in authority.db.search_sessions(source=sources, local_created_sources=[family], limit=50,
- workspace_key=scope, min_message_count=1):
+ workspace_key=scope, skip_launch_stubs=True):
tip = authority.db.get_compression_tip(row['id']) or row['id']
try:
return resolve_local_target(authority, actor, tip)
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 01234d8f460..ab5bf578965 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -1343,11 +1343,11 @@ def _resolve_last_session(source: str = "cli") -> Optional[str]:
with _session_db() as db:
ws_key = _resolve_workspace_key()
if ws_key:
- sessions = db.search_sessions(source=source, limit=1, workspace_key=ws_key, min_message_count=1)
+ sessions = db.search_sessions(source=source, limit=1, workspace_key=ws_key, skip_launch_stubs=True)
if sessions:
return sessions[0]["id"]
# Fallback: global MRU for this source.
- sessions = db.search_sessions(source=source, limit=1, min_message_count=1)
+ sessions = db.search_sessions(source=source, limit=1, skip_launch_stubs=True)
return sessions[0]["id"] if sessions else None
return None
diff --git a/hermes_state_common.py b/hermes_state_common.py
index b2aaeeb125a..c31526f02c6 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -359,6 +359,22 @@ def _placeholders(items) -> str:
return ",".join("?" for _ in range(items if isinstance(items, int) else len(items)))
+# A first prompt is durable in ``session_admissions`` from admission on, while its transcript row lands
+# only at turn start; a restart in between leaves the admission ``unknown`` and the session at 0
+# messages. Only a session with neither messages nor an admission is an empty launch stub.
+_NOT_A_LAUNCH_STUB_SQL = (
+ "(s.message_count > 0 OR EXISTS (SELECT 1 FROM session_admissions a WHERE a.target_session_id = s.id))")
+
+
+def launch_stub_filter_sql(db) -> str:
+ """``sessions s`` predicate that drops empty launch stubs (the CLI crashed or a resume failed before
+ the first turn). A read-only open does not migrate, so a store from before the runtime tables may
+ lack ``session_admissions``; messages alone decide there."""
+ if db._read_all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_admissions'"):
+ return _NOT_A_LAUNCH_STUB_SQL
+ return "s.message_count > 0"
+
+
def _source_match_clause(sources, local_created_sources=None) -> tuple[str, list]:
"""``sessions s`` source predicate. With ``local_created_sources``, a ``source='local'`` row
matches only when ``created_source`` is one of those surfaces; the placeholder ``'unknown'``
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index 46b855a0312..5de4d7624dd 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -21,7 +21,7 @@ from hermes_state_common import (
_shape_preview, _sql_preview_raw, QUEUED_PROMPT_METADATA_KEY,
_sql_in_window, _sql_json_extract, _sql_session_last_active, _sql_session_last_active_by_id,
escape_like as _escape_like, _SQL_IN_CHUNK, _id_chunks, _placeholders as _session_ids_placeholders,
- _source_match_clause, emit_session_deleted,
+ _source_match_clause, emit_session_deleted, launch_stub_filter_sql,
)
from hermes_state_compression import _CHAIN_CAP
@@ -1547,14 +1547,14 @@ class SessionSessionsMixin:
def search_sessions(
self, source: str | Sequence[str] | None = None, limit: int = 20, offset: int = 0,
workspace_key: str | None = None, local_created_sources: Sequence[str] | None = None,
- min_message_count: int = 0,
+ skip_launch_stubs: bool = False,
) -> list[dict[str, Any]]:
"""Sessions MRU-first with a computed ``last_active``; ``workspace_key`` scopes to one workspace
so ``hermes -c``/``--resume`` picks its last session. ``source`` may be one label or several.
``local_created_sources`` restricts ``source='local'`` rows before LIMIT/OFFSET, and
- ``min_message_count`` drops shorter rows (empty launch stubs) before it too."""
- where_clauses = ["s.message_count >= ?"] if min_message_count > 0 else []
- params: list = [min_message_count] if min_message_count > 0 else []
+ ``skip_launch_stubs`` drops empty launch stubs (launch_stub_filter_sql) before it too."""
+ where_clauses = [launch_stub_filter_sql(self)] if skip_launch_stubs else []
+ params: list = []
if source:
sources = [source] if isinstance(source, str) else list(source)
clause, bound = _source_match_clause(sources, local_created_sources)
diff --git a/tests/gateway/test_resume_latest_local_cli.py b/tests/gateway/test_resume_latest_local_cli.py
index cf6ae953ed3..3e09adb814b 100644
--- a/tests/gateway/test_resume_latest_local_cli.py
+++ b/tests/gateway/test_resume_latest_local_cli.py
@@ -175,9 +175,12 @@ async def test_oneshot_keeps_its_own_created_source_and_stays_out_of_cli(tmp_pat
@pytest.mark.asyncio
-async def test_latest_skips_a_newer_empty_launch_stub(tmp_path, monkeypatch):
[email protected]('admission', [None, 'queued', 'unknown'])
+async def test_latest_skips_a_newer_empty_launch_stub(tmp_path, monkeypatch, admission):
"""CLI-31: the insert stamps the surface, so a 0-message launch stub left by a crash or a
- failed resume is the newest CLI row. Neither ``session.resume latest`` nor ``-c`` picks it."""
+ failed resume is the newest CLI row. Neither ``session.resume latest`` nor ``-c`` picks it.
+ A newer session whose first prompt is admitted (queued, or ``unknown`` after a restart) but
+ not yet written is a conversation, not a stub: both still pick it."""
store, authority, owner = _owner(tmp_path / 'home', monkeypatch)
try:
ids = []
@@ -192,16 +195,22 @@ async def test_latest_skips_a_newer_empty_launch_stub(tmp_path, monkeypatch):
authority.db.append_message(real, 'user', 'hello')
with authority.db._lock:
authority.db._conn.execute("UPDATE sessions SET started_at = started_at + 60 WHERE id = ?", (stub,))
+ if admission:
+ authority.db._conn.execute(
+ "INSERT INTO session_admissions(admission_id,request_id,principal_id,target_session_id,"
+ "lineage_json,payload_json,payload_digest,intent,status) "
+ "VALUES('adm','req','human',?,'[]','{}','d','queue',?)", (stub, admission))
authority.db._conn.commit()
authority.sessions.clear()
-
- resumed = await _call(owner, 'session.resume', latest='cli')
- assert isinstance(resumed, dict) and resumed['session_id'] == real, resumed
+ expected = stub if admission else real
from hermes_cli.main import _resolve_last_session
monkeypatch.setattr('hermes_cli.main._resolve_workspace_key', lambda: None)
monkeypatch.setattr('hermes_cli.main.get_hermes_home', lambda: authority.db.db_path.parent)
- assert _resolve_last_session('cli') == real
+ assert _resolve_last_session('cli') == expected
+
+ resumed = await _call(owner, 'session.resume', latest='cli')
+ assert isinstance(resumed, dict) and resumed['session_id'] == expected, resumed
finally:
await owner.close()
store.close_all_db_handles()