The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): page CLI sessions by creating surface before the limit
David Dudok de Witdc4da1a347d4
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 622fe2cbe8b..89b07bdf1c3 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -348,7 +348,11 @@ _LOCAL_LABELLED = frozenset({"cli", "tui", "gui"})class SurfaceLabelReader:"""A read-only ``SessionDB`` whose source-filtered listings read main's labels: ``source='cli'``also matches a gateway row labelled ``local`` that the CLI created (``created_source='cli'``), so- main's /resume picker, /sessions, /history and bare ``-c`` find the sessions the CLI made."""+ main's /resume picker, /sessions, /history and bare ``-c`` find the sessions the CLI made.++ The surface predicate runs in SQL before LIMIT/OFFSET. Filtering a fixed over-fetch of every+ ``local`` row dropped CLI sessions once newer Desktop/TUI rows filled that window.+ """def __init__(self, db):self._wrapped = db@@ -356,26 +360,29 @@ class SurfaceLabelReader:def __getattr__(self, name):return getattr(self._wrapped, name)- def _labelled(self, method, requested, limit, offset, call):+ def _labelled(self, requested, limit, offset, call):wanted = {requested} if isinstance(requested, str) else set(requested or ())surfaces = wanted & _LOCAL_LABELLEDif not surfaces:- return call(requested, limit, offset)- # Over-fetch, then keep only the local rows those surfaces created (ordering is the reader's own).- rows = call(sorted(wanted | {"local"}), (limit + offset) * 3 + 50, 0)- kept = [row for row in rows if row.get("source") != "local" or row.get("created_source") in surfaces]- return kept[offset:offset + limit]+ return call(requested, limit, offset, None)+ # ``local`` is the gateway label; ``created_source`` is the surface. Page the rows this+ # surface can see, not a window of every local row.+ return call(sorted(wanted | {"local"}), limit, offset, sorted(surfaces))def search_sessions(self, source=None, limit=20, offset=0, **kw):- return self._labelled("search_sessions", source, limit, offset,- lambda src, lim, off: self._wrapped.search_sessions(source=src, limit=lim, offset=off, **kw))+ return self._labelled(+ source, limit, offset,+ lambda src, lim, off, surfaces: self._wrapped.search_sessions(+ source=src, limit=lim, offset=off, local_created_sources=surfaces, **kw))def list_sessions_rich(self, source=None, sources=None, limit=20, offset=0, **kw):requested = sources if sources else ([source] if source else None)if not requested:return self._wrapped.list_sessions_rich(limit=limit, offset=offset, **kw)- return self._labelled("list_sessions_rich", requested, limit, offset,- lambda src, lim, off: self._wrapped.list_sessions_rich(sources=src, limit=lim, offset=off, **kw))+ return self._labelled(+ requested, limit, offset,+ lambda src, lim, off, surfaces: self._wrapped.list_sessions_rich(+ sources=src, limit=lim, offset=off, local_created_sources=surfaces, **kw))_CANONICAL_LOCAL_ID = re.compile(r"^local-([0-9a-f]{8})[0-9a-f]{56}$")diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 2c457853dd5..6ddf8e75acc 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -354,6 +354,31 @@ def _placeholders(items) -> str:return ",".join("?" for _ in range(items if isinstance(items, int) else len(items)))+def _source_match_clause(sources, local_created_sources=None) -> tuple[str, list]:+ """``sessions s`` source predicate, applied before LIMIT/OFFSET.++ With ``local_created_sources``, a ``source='local'`` row matches only when+ ``created_source`` is one of those surfaces. Every other requested source+ matches on its own label, whatever ``created_source`` says. A placeholder+ ``created_source='unknown'`` is not a surface: it stays unmatched until an+ upsert stamps the real creator (#138838, #139058).+ """+ labels = list(sources or [])+ if not labels:+ return "", []+ surfaces = [item for item in (local_created_sources or ()) if item]+ if not surfaces:+ return f"s.source IN ({_placeholders(labels)})", labels+ non_local = [item for item in labels if item != "local"]+ local_sql = f"(s.source = 'local' AND s.created_source IN ({_placeholders(surfaces)}))"+ if not non_local:+ return local_sql, list(surfaces)+ return (+ f"(s.source IN ({_placeholders(non_local)}) OR {local_sql})",+ [*non_local, *surfaces],+ )++# Ids per ``IN (?,...)`` list: SQLite caps bound parameters at SQLITE_MAX_VARIABLE_NUMBER (999 on builds# < 3.32, 32766 after); a bulk prune of a cron-heavy store bound tens of thousands of ids into one list and# died with "too many SQL variables". Every IN-list over session ids goes through ``_id_chunks``.@@ -811,6 +836,13 @@ CREATE INDEX IF NOT EXISTS idx_sessions_tool_names-- a small candidate set before compression-chain and preview hydration.CREATE INDEX IF NOT EXISTS idx_sessions_effective_activityON sessions(COALESCE(last_activity_at, started_at) DESC, started_at DESC);+-- CLI/TUI listings match gateway rows stored as source='local' by created_source,+-- before LIMIT. created_source is reconciled onto legacy DBs, so this index lives+-- here rather than in SCHEMA_SQL. A source-only index would walk every local row+-- (Desktop and TUI included) to find one surface.+CREATE INDEX IF NOT EXISTS idx_sessions_local_created_started+ ON sessions(created_source, started_at DESC)+ WHERE source = 'local';"""diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex ce2032608b8..0df19d18d3c 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -22,6 +22,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,)from hermes_state_compression import _CHAIN_CAP@@ -113,7 +114,7 @@ def _session_filter_where(*, exclude_children: bool = False, source: str | None = None, sources: list[str] | None = None,session_key: str | None = None, exclude_sources: list[str] | None = None, cwd_prefix: str | None = None,min_message_count: int = 0, archived_only: bool = False, include_archived: bool = False,- include_subagents: bool = False,+ include_subagents: bool = False, local_created_sources: Sequence[str] | None = None,) -> tuple[list[str], list[Any]]:"""Shared ``sessions s`` WHERE builder so counts line up with listed rows. ``exclude_children``hides sub-agent runs and compression continuations but keeps branch/reset children@@ -134,8 +135,9 @@ def _session_filter_where(# legacy heuristic (parent ended with 'branched' before the child started), covering branch sessions# created before the marker existed.include_sources = [source] if source else list(sources or [])+ source_clause, source_params = _source_match_clause(include_sources, local_created_sources)for clause, values in (- (f"s.source IN ({_session_ids_placeholders(include_sources)})", include_sources),+ (source_clause, source_params),("s.session_key = ?", [session_key] if session_key else []),(f"s.source NOT IN ({_session_ids_placeholders(exclude_sources or ())})", exclude_sources or []),(_cwd_prefix_clause(cwd_prefix) if cwd_prefix else ("", [])),@@ -1325,18 +1327,20 @@ class SessionSessionsMixin:order_by_last_active: bool = False, include_archived: bool = False, archived_only: bool = False,id_query: str | None = None, search_query: str | None = None, compact_rows: bool = False,include_pinned: bool = False, session_key: str | None = None, include_hidden: bool = False,- include_subagents: bool = False,+ include_subagents: bool = False, local_created_sources: Sequence[str] | None = None,) -> list[dict[str, Any]]:"""List sessions with preview and ``last_active`` in one query. ``order_by_last_active`` sortsby the chain TIP via a recursive CTE (the only path honouring ``id_query`` / ``search_query``);``include_pinned`` back-fills pins the page missed, still obeying the otherfilters except archived: a pin is an explicit keep, so a pinned row stamped- archived must still return."""+ archived must still return. ``local_created_sources`` restricts ``source='local'``+ rows to those surfaces before LIMIT/OFFSET."""self.flush_token_counts() # rows carry token/cost totalswhere_clauses, params = _session_filter_where(exclude_children=not include_children, source=source, sources=sources, session_key=session_key,exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, min_message_count=min_message_count,archived_only=archived_only, include_archived=include_archived, include_subagents=include_subagents,+ local_created_sources=local_created_sources,)# The archived-only view is the recovery surface for rows that dropped out of every# default list: a session that is archived AND hidden (Bot Mode marks its sessions@@ -1420,7 +1424,7 @@ class SessionSessionsMixin:exclude_children=not include_children, source=source, sources=sources,session_key=session_key, exclude_sources=exclude_sources, cwd_prefix=cwd_prefix,min_message_count=min_message_count, archived_only=False, include_archived=True,- include_subagents=include_subagents,+ include_subagents=include_subagents, local_created_sources=local_created_sources,)if not include_hidden and not archived_only:pinned_clauses.append("s.hidden = 0")@@ -1532,16 +1536,18 @@ class SessionSessionsMixin:def search_sessions(self, source: str | Sequence[str] | None = None, limit: int = 20, offset: int = 0,- workspace_key: str | None = None,+ workspace_key: str | None = None, local_created_sources: Sequence[str] | None = None,) -> 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."""+ 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."""where_clauses = []params: list = []if source:sources = [source] if isinstance(source, str) else list(source)- where_clauses.append(f"s.source IN ({','.join('?' * len(sources))})")- params.extend(sources)+ clause, bound = _source_match_clause(sources, local_created_sources)+ where_clauses.append(clause)+ params.extend(bound)if workspace_key:ws_clause, ws_params = _workspace_key_clause(workspace_key)where_clauses.append(ws_clause)@@ -1559,12 +1565,14 @@ class SessionSessionsMixin:self, source: str | None = None, sources: list[str] | None = None, cwd_prefix: str | None = None,min_message_count: int = 0, include_archived: bool = False, archived_only: bool = False,exclude_children: bool = False, exclude_sources: list[str] | None = None, include_subagents: bool = False,+ local_created_sources: Sequence[str] | None = None,) -> int:"""Count sessions with list_sessions_rich's filters so a paired "load more" total matches."""where_clauses, params = _session_filter_where(exclude_children=exclude_children, source=source, sources=sources,exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, min_message_count=min_message_count,archived_only=archived_only, include_archived=include_archived, include_subagents=include_subagents,+ local_created_sources=local_created_sources,)if exclude_children:from hermes_state_local import exclude_superseded_segmentsdiff --git a/tests/agent/test_insights.py b/tests/agent/test_insights.pyindex e770f348340..60ff979af5f 100644--- a/tests/agent/test_insights.py+++ b/tests/agent/test_insights.py@@ -614,6 +614,8 @@ def test_source_filter_includes_gateway_local_rows_that_surface_created(db):def test_source_filter_on_a_db_without_created_source(db):"""A DB an older writer left behind (read-only opens skip migrations) still filters by label."""_label(db, "legacy-cli", "cli", "cli")+ # SQLite refuses DROP COLUMN while an index references the column.+ db._conn.execute("DROP INDEX IF EXISTS idx_sessions_local_created_started")db._conn.execute("ALTER TABLE sessions DROP COLUMN created_source")db._conn.commit()assert InsightsEngine(db).generate(days=30, source="cli")["overview"]["total_sessions"] == 1diff --git a/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.py b/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.pynew file mode 100644index 00000000000..22f9ff95475--- /dev/null+++ b/tests/hermes_cli/test_cli_sessions_behind_newer_surfaces.py@@ -0,0 +1,260 @@+"""CLI session lookups must page by creating surface, not by a fixed local window.++Gateway rows for Desktop, TUI and the classic CLI are stored as ``source='local'``+with the real surface in ``created_source``. ``hermes -c``, in-chat ``/sessions``+and ``/resume`` read those rows through ``SurfaceLabelReader``. A fixed over-fetch+of every local row, filtered afterwards, drops the CLI session once enough newer+Desktop/TUI rows fill the window. ``hermes sessions list`` does not use that reader.++``created_source='unknown'`` stays unmatched. #138838 and #139058 repair that+placeholder on upsert; this reader does not admit it.+"""++from __future__ import annotations++from types import SimpleNamespace++from hermes_state import SessionDB+++def _populate(db: SessionDB, rows: list[tuple[str, str, str, float]]) -> None:+ for sid, source, _created, _started in rows:+ db.create_session(sid, source=source)+ with db._lock:+ db._conn.executemany(+ "UPDATE sessions SET created_source=?, started_at=? WHERE id=?",+ [(created, started, sid) for sid, _source, created, started in rows],+ )+ db._conn.commit()+++def _newer_locals(count: int, *, start: float, prefix: str) -> list[tuple[str, str, str, float]]:+ """``count`` gateway rows newer than a CLI session, alternating Desktop and TUI."""+ surfaces = ("desktop", "tui")+ return [+ (f"{prefix}-{index:03d}", "local", surfaces[index % 2], start + index)+ for index in range(count)+ ]+++def _cli_row(sid: str, started: float, *, source: str = "local", created: str = "cli"):+ return (sid, source, created, started)+++def _resolve_cli(monkeypatch, home) -> str | None:+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr("hermes_cli.main._resolve_workspace_key", lambda: None)+ from hermes_cli.main import _resolve_last_session++ return _resolve_last_session("cli")+++def _recent_cli_ids(db: SessionDB) -> tuple[list[str], list[str]]:+ """Ids from the shared listing helper and from ``/sessions`` / ``/resume`` (limit 10)."""+ from hermes_cli.cli_session_mixin import CLISessionMixin+ from hermes_cli.gateway_session_store import SurfaceLabelReader+ from hermes_cli.session_listing import query_session_listing+ from hermes_state_sessions import INTERNAL_LISTING_SOURCES++ reader = SurfaceLabelReader(db)+ listed = query_session_listing(+ reader,+ source="cli",+ current_session_id="other-session",+ include_all_sources=False,+ include_unnamed=True,+ limit=10,+ exclude_sources=list(INTERNAL_LISTING_SOURCES),+ )+ via_command = CLISessionMixin._list_recent_sessions(+ SimpleNamespace(_session_db=reader, session_id="other-session"),+ limit=10,+ )+ return [row["id"] for row in listed], [row["id"] for row in via_command]+++def _reader_ids(db: SessionDB, method: str, **kwargs) -> list[str]:+ from hermes_cli.gateway_session_store import SurfaceLabelReader++ rows = getattr(SurfaceLabelReader(db), method)(**kwargs)+ return [row["id"] for row in rows]+++def test_continue_finds_cli_session_behind_sixty_newer_desktop_sessions(tmp_path, monkeypatch):+ """Bare ``hermes -c`` resolves the CLI session even when 60 newer Desktop/TUI rows exist."""+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ *_newer_locals(60, start=2_000_000, prefix="desk"),+ ])+ db.close()++ assert _resolve_cli(monkeypatch, tmp_path) == "cli-session"+++def test_sessions_and_resume_list_cli_session_behind_two_hundred_newer_rows(tmp_path):+ """In-chat ``/sessions`` and ``/resume`` still list the CLI session behind 200 newer rows."""+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ *_newer_locals(200, start=3_000_000, prefix="newer"),+ ])++ listed, via_command = _recent_cli_ids(db)+ assert listed == ["cli-session"]+ assert via_command == ["cli-session"]+ db.close()+++def test_surface_pages_are_exact_across_newer_local_rows(tmp_path):+ """LIMIT/OFFSET walk matching rows, including across Desktop/TUI rows that sit between them.++ A non-local ``source='cli'`` row still matches when ``created_source`` names another+ surface. ``unknown``, Desktop, TUI and an unrelated platform do not.+ """+ rows = [+ ("telegram-new", "telegram", "telegram", 2_100_000),+ ("unknown-new", "local", "unknown", 2_000_000),+ *_newer_locals(60, start=1_900_000, prefix="top"),+ _cli_row("legacy-cli", 1_800_000, source="cli", created="desktop"),+ *_newer_locals(10, start=1_700_000, prefix="gap-a"),+ _cli_row("cli-a", 1_600_000),+ *_newer_locals(10, start=1_500_000, prefix="gap-b"),+ _cli_row("cli-b", 1_400_000),+ *_newer_locals(10, start=1_300_000, prefix="gap-c"),+ _cli_row("cli-c", 1_200_000),+ ]+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, rows)+ expected = ["legacy-cli", "cli-a", "cli-b", "cli-c"]++ for method in ("search_sessions", "list_sessions_rich"):+ kwargs = {"source": "cli"}+ assert _reader_ids(db, method, limit=10, **kwargs) == expected+ assert _reader_ids(db, method, limit=2, offset=0, **kwargs) == ["legacy-cli", "cli-a"]+ assert _reader_ids(db, method, limit=1, offset=1, **kwargs) == ["cli-a"]+ assert _reader_ids(db, method, limit=2, offset=2, **kwargs) == ["cli-b", "cli-c"]+ # ``hermes -c`` asks for the CLI family (cli + oneshot), still paged in SQL.+ assert _reader_ids(db, "search_sessions", source=["cli", "oneshot"], limit=1) == ["legacy-cli"]+ db.close()+++def test_continue_and_sessions_find_a_lone_cli_session(tmp_path, monkeypatch):+ """Control: with no newer Desktop/TUI rows, both surfaces already find the CLI session."""+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [_cli_row("cli-session", 1_000_000)])+ listed, via_command = _recent_cli_ids(db)+ db.close()++ assert listed == ["cli-session"]+ assert via_command == ["cli-session"]+ assert _resolve_cli(monkeypatch, tmp_path) == "cli-session"+++def test_unknown_placeholder_does_not_become_the_cli_mru(tmp_path, monkeypatch):+ """Control: a newer ``created_source='unknown'`` local row is not CLI history.++ #138838 and #139058 repair that placeholder on the creator upsert. Widening this+ reader to admit it would duplicate those fixes and hide the real CLI session.+ """+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ ("unknown-new", "local", "unknown", 2_000_000),+ ])+ db.close()++ assert _resolve_cli(monkeypatch, tmp_path) == "cli-session"+++def test_oneshot_remains_cli_family_mru(tmp_path, monkeypatch):+ """Control: a finite CLI run (``source='oneshot'``) is still the ``-c`` MRU when it is newest."""+ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ ("shot", "oneshot", "oneshot", 2_000_000),+ ])+ db.close()++ assert _resolve_cli(monkeypatch, tmp_path) == "shot"+++def _plans_for_surface_reads(db: SessionDB) -> list[str]:+ """EXPLAIN QUERY PLAN text for the surface-filtered SELECTs the reader actually runs."""+ from hermes_cli.gateway_session_store import SurfaceLabelReader++ captured: list[tuple[str, tuple]] = []+ original = db._read_all++ def _capture(sql, params=()):+ captured.append((sql, tuple(params)))+ return original(sql, params)++ db._read_all = _capture+ reader = SurfaceLabelReader(db)+ reader.search_sessions(source=["cli", "oneshot"], limit=1)+ reader.list_sessions_rich(source="cli", limit=10, offset=2)+ plans = []+ for sql, params in captured:+ if "created_source" not in sql:+ continue+ rows = db._conn.execute("EXPLAIN QUERY PLAN " + sql, params).fetchall()+ plans.append("\n".join(row["detail"] if hasattr(row, "keys") else row[3] for row in rows))+ return plans+++def test_surface_filter_seeks_the_local_created_source_index(tmp_path):+ """The local branch seeks ``created_source`` instead of scanning every local row.++ Startup recreates the partial index on a store that predates it (the index is+ declared with the other post-reconcile indexes).+ """+ path = tmp_path / "state.db"+ db = SessionDB(db_path=path)+ db._conn.execute("DROP INDEX IF EXISTS idx_sessions_local_created_started")+ db._conn.commit()+ db.close()++ db = SessionDB(db_path=path)+ present = db._conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?",+ ("idx_sessions_local_created_started",),+ ).fetchone()+ assert present is not None+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ *_newer_locals(30, start=2_000_000, prefix="desk"),+ ])+ plans = _plans_for_surface_reads(db)+ assert plans, "surface-filtered reads did not reach SQL"+ for plan in plans:+ assert "idx_sessions_local_created_started" in plan+ assert "SCAN s" not in plan+ assert "SCAN sessions" not in plan+ db.close()+++def test_sessions_list_stays_a_recency_page_across_surfaces(tmp_path, capsys):+ """Control: ``hermes sessions list`` does not apply the CLI surface window.++ The default page is the newest rows of every source. A limit that reaches the older+ CLI row includes it together with the Desktop rows, the same as an unfiltered read.+ """+ from hermes_cli.sessions_cmd import _cmd_list++ db = SessionDB(db_path=tmp_path / "state.db")+ _populate(db, [+ _cli_row("cli-session", 1_000_000),+ *_newer_locals(60, start=2_000_000, prefix="desk"),+ ])++ _cmd_list(db, SimpleNamespace(limit=20, source=None, workspace=None))+ short = capsys.readouterr().out+ assert "cli-session" not in short+ assert "desk-059" in short++ _cmd_list(db, SimpleNamespace(limit=80, source=None, workspace=None))+ full = capsys.readouterr().out+ assert "cli-session" in full+ assert "desk-059" in full+ db.close()