The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): never resume an empty launch stub as the latest session
kshitijk4poorbc4de990262e
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.pyindex 7a929f805b7..1a4aa945f28 100644--- a/gateway/session_local_title.py+++ b/gateway/session_local_title.py@@ -48,8 +48,10 @@ def resolve_latest_session(authority, actor, family, workspace=None):# The owner's own rows are stored ``local``, with the family in ``created_source``.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".for row in authority.db.search_sessions(source=sources, local_created_sources=[family], limit=50,- workspace_key=scope):+ workspace_key=scope, min_message_count=1):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.pyindex 40cc1e34d76..9b2acf1f4d6 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1340,14 +1340,14 @@ def _resolve_last_session(source: str = "cli") -> Optional[str]:if source == "cli":from agent.session_source import CLI_FAMILY_SOURCESsource = sorted(CLI_FAMILY_SOURCES)- with _session_db() as db:+ with _session_db() as db: # min_message_count: an empty launch stub never wins (resolve_latest_session)ws_key = _resolve_workspace_key()if ws_key:- sessions = db.search_sessions(source=source, limit=1, workspace_key=ws_key)+ sessions = db.search_sessions(source=source, limit=1, workspace_key=ws_key, min_message_count=1)if sessions:return sessions[0]["id"]# Fallback: global MRU for this source.- sessions = db.search_sessions(source=source, limit=1)+ sessions = db.search_sessions(source=source, limit=1, min_message_count=1)return sessions[0]["id"] if sessions else Nonereturn Nonediff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex b166cb006bf..c93e9ca42de 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -1551,12 +1551,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,) -> list[dict[str, Any]]:"""Sessions MRU-first with a computed ``last_active``; ``workspace_key`` scopes to one workspaceso ``hermes -c``/``--resume`` picks its last session. ``source`` may be one label or several.- ``local_created_sources`` restricts ``source='local'`` rows before LIMIT/OFFSET."""- where_clauses = []- params: list = []+ ``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 []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.pyindex 67cd166d457..0336e441e33 100644--- a/tests/gateway/test_resume_latest_local_cli.py+++ b/tests/gateway/test_resume_latest_local_cli.py@@ -60,6 +60,7 @@ async def test_resume_latest_matches_the_owners_local_rows_by_creating_surface(tauthority.db.create_session(sid, source=SURFACES[surface])live = authority.sessions[sid]store._record_gateway_session_peer(sid, live.route, live.source)+ authority.db.append_message(sid, 'user', 'hi')rows = {sid: authority.db.get_session(sid) for sid in created.values()}assert {(row['source'], row['created_source']) for row in rows.values()} == {('local', 'cli'), ('local', 'tui'), ('local', 'desktop')}@@ -89,6 +90,7 @@ async def test_auxiliary_usage_cannot_replace_the_insert_stamp(tmp_path, monkeypauthority.db.record_auxiliary_usage(sid, 'compression', model='m', input_tokens=4, output_tokens=1)live = authority.sessions[sid]store._record_gateway_session_peer(sid, live.route, live.source)+ authority.db.append_message(sid, 'user', 'hi')authority.sessions.clear()resumed = await _call(owner, 'session.resume', latest='cli')assert isinstance(resumed, dict) and resumed['session_id'] == sid, resumed@@ -217,6 +219,7 @@ async def test_worker_create_after_peer_refresh_still_resumes(tmp_path, monkeypastore._record_gateway_session_peer(sid, live.route, live.source)with pytest.raises(RuntimeStoreError, match='permission_denied'):authority.db._execute_write(lambda conn: worker_create(authority.db, conn, sid, {'source': 'cli'}))+ authority.db.append_message(sid, 'user', 'hi')authority.sessions.clear()resumed = await _call(owner, 'session.resume', latest='cli')assert isinstance(resumed, dict) and resumed['session_id'] == sid, resumed@@ -252,3 +255,36 @@ async def test_gui_and_acp_list_under_the_policy_label_and_the_agent_surface(finally:await owner.close()store.close_all_db_handles()+++async def test_latest_skips_a_newer_empty_launch_stub(tmp_path, monkeypatch):+ """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."""+ store, authority, owner = _owner(tmp_path / 'home', monkeypatch)+ try:+ ids = []+ for name in ('real', 'stub'):+ created = await _call(owner, 'session.create', request_id=name, source='cli',+ cwd=str(tmp_path), toolsets=[], model='m')+ ids.append(sid := created['session_id'])+ authority.db.create_session(sid, source='cli')+ live = authority.sessions[sid]+ store._record_gateway_session_peer(sid, live.route, live.source)+ real, stub = ids+ 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,))+ 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++ 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+ finally:+ await owner.close()+ store.close_all_db_handles()diff --git a/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.py b/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.pyindex b80499e8b62..b4117759eb9 100644--- a/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.py+++ b/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.py@@ -24,7 +24,7 @@ def _populate(db: SessionDB, rows: list[tuple[str, str, str, float]]) -> None:db.create_session(sid, source=source)with db._lock:db._conn.executemany(- "UPDATE sessions SET created_source=?, started_at=? WHERE id=?",+ "UPDATE sessions SET created_source=?, started_at=?, message_count=1 WHERE id=?",[(created, started, sid) for sid, _source, created, started in rows],)db._conn.commit()@@ -129,6 +129,7 @@ def _pre_column_readonly(tmp_path) -> SessionDB:writer = SessionDB(db_path=path)writer.create_session("legacy-cli", source="cli")with writer._lock:+ writer._conn.execute("UPDATE sessions SET message_count=1 WHERE id='legacy-cli'")writer._conn.execute("DROP INDEX IF EXISTS idx_sessions_local_created_started")writer._conn.execute("ALTER TABLE sessions DROP COLUMN created_source")writer._conn.commit()diff --git a/tests/hermes_cli/test_resolve_last_session.py b/tests/hermes_cli/test_resolve_last_session.pyindex 77b2298b47e..f78c5f09e0f 100644--- a/tests/hermes_cli/test_resolve_last_session.py+++ b/tests/hermes_cli/test_resolve_last_session.py@@ -68,8 +68,9 @@ def test_resolve_last_session_real_db_prefers_workspace(monkeypatch, tmp_path):db.create_session("repo_a", source="cli", cwd=str(repo_a), git_repo_root=str(repo_a))db.create_session("repo_b", source="cli", cwd="/other/repo-b", git_repo_root="/other/repo-b")with db._lock:- db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (100.0, "repo_a"))- db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (9000.0, "repo_b"))+ # One message each: ``-c`` never resumes an empty launch stub.+ db._conn.execute("UPDATE sessions SET started_at=?, message_count=1 WHERE id=?", (100.0, "repo_a"))+ db._conn.execute("UPDATE sessions SET started_at=?, message_count=1 WHERE id=?", (9000.0, "repo_b"))db._conn.commit()finally:db.close()@@ -101,7 +102,7 @@ def test_resolve_last_session_cli_continues_a_oneshot(monkeypatch, tmp_path):db.create_session("tui_chat", source="tui")with db._lock:for sid, started in (("interactive", 100.0), ("oneshot_run", 200.0), ("tui_chat", 300.0)):- db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (started, sid))+ db._conn.execute("UPDATE sessions SET started_at=?, message_count=1 WHERE id=?", (started, sid))db._conn.commit()finally:db.close()