The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: keep dashboard session browsing read-only
Tekniumaf4599c10738
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex eb4450c0ccb..b7673ceb2be 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -19,7 +19,7 @@ from fastapi.responses import StreamingResponsefrom hermes_cli.web_deps import latefrom hermes_cli.web_server_gateway import _strip_session_list_rows-from hermes_cli.web_server_sessions import _maybe_auto_archive_for_profile, _session_latest_descendant+from hermes_cli.web_server_sessions import _session_latest_descendantfrom hermes_cli.web_models import (BulkDeleteSessions, SessionImport, SessionOwnerBackfill, SessionPrune, SessionRename)from hermes_cli.web_routers._common import log as _log, http_failure@@ -181,9 +181,6 @@ def get_sessions(raise HTTPException(status_code=400, detail="order must be one of: created, recent")profile_name = _cron_profile_home(profile)[0] if profile else Nonetry:- # Auto-archive is the only write on this GET path: run it on its own- # maintenance connection, then open the listing connection read-only.- _maybe_auto_archive_for_profile(profile)db = _open_session_db_for_profile(profile, read_only=True)try:min_message_count = max(0, min_messages)diff --git a/hermes_cli/web_server_app.py b/hermes_cli/web_server_app.pyindex 000052506a5..f24cee3625c 100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@ -31,7 +31,7 @@ async def standalone_lifespan(app: "FastAPI"):# Bring state.db schema current BEFORE the first session-list poll# (#79531/#80037): a store left behind by `hermes update` otherwise 500s- # every poll while the read-probe heal loses to sibling lock contention.+ # every poll until its owner completes schema reconciliation.# Daemon thread so a locked store never delays the socket (Desktop# ready-probe times out at 10s, GH-73083).threading.Thread(diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex 14b554628cd..907478a3e73 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -171,8 +171,8 @@ def _eager_reconcile_own_session_db() -> None:"""One writable open of this process's own state.db at startup.``SessionDB.__init__`` runs ``_init_schema`` → ``_reconcile_columns`` with- open-time lock patience. Never raises: an unfixable store still gets the- per-poll read-probe heal in :func:`_open_session_db_at_path`.+ open-time lock patience. Never raises: unavailable stores are reported by+ read-only browsing until their owner initializes or repairs them."""try:from hermes_state import _default_db_path@@ -183,7 +183,7 @@ def _eager_reconcile_own_session_db() -> None:except Exception as exc:_log.warning("startup schema reconcile of state.db failed (%s); session "- "reads will retry the heal per poll", exc,+ "reads will report the store unavailable until owner recovery", exc,)diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex 106288207df..5dd2e38340d 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -1,10 +1,8 @@-"""Session-DB access for the dashboard: per-profile SessionDB opening with schema-heal, latest-descendant lookup and the auto-archive ticker.+"""Read-only session browsing, latest-descendant lookup and owner maintenance."""import loggingimport asyncio-import threadingimport timefrom pathlib import Pathfrom typing import Dict, Optional@@ -68,116 +66,58 @@ def _session_latest_descendant(session_id: str, db):return current, path-# Serialises the one-time writable schema bootstrap for read-only opens, so-# concurrent first-load polls don't open mode=ro against a half-written schema-# ("no such table: sessions").-_session_db_bootstrap_lock = threading.Lock()--def _session_db_read_probe_statements() -> tuple:- """Stale-schema probes for read-only opens (which skip _reconcile_columns()).- Derived from SCHEMA_SQL so a new column is probed automatically — a- hand-written list once went stale and emptied the sidebar after update."""+ """Probe the declared schema without reconciling it on a browsing request."""from hermes_state_schema import schema_read_probe_statementsreturn schema_read_probe_statements()-# Stores where a heal WRITABLE OPEN SUCCEEDED but the read probe still failed:-# one reconciliation cannot fix them (e.g. a NOT-NULL-without-default column),-# so they fall back to the raw read-only open until restart instead of paying-# a writable init per poll. A FAILED writable open (transient lock) is NOT-# recorded — the next poll retries the heal.-_session_db_heal_exhausted: set = set()--# Deduplicates the heal-failure warning per store per process.-_session_db_heal_warned: set = set()---def _is_stale_schema_error(exc: BaseException) -> bool:- message = str(exc).lower()- return "no such table" in message or "no such column" in message--def _open_session_db_at_path(db_path: Path, *, read_only: bool):- """Open a SessionDB at an explicit path with an explicit access mode.+ """Browsing never initializes, repairs or upgrades the owner's session store.- Read-only opens bootstrap a missing/zero-byte store once and heal a stale or- malformed schema through ONE writable open before reopening read-only; the- healthy read path never takes a write lock. Tables outside SCHEMA_SQL- (telemetry ``tel_*``, FTS shadow tables) are outside both probe and heal.+ Owner startup reconciles schema; explicit mutation APIs retain their writable+ acquisition until their separate owner-RPC migration."""import sqlite3- from hermes_state import SessionDB, is_malformed_schema_error- from hermes_state_registry import acquire, release_or_close+ from fastapi import HTTPException+ from hermes_state import SessionDB+ from hermes_state_errors import is_transient_sqlite_error+ from hermes_state_registry import acquire- # Read-only file/sidecar preflight (port of kilocode#12508): repair-or-refuse BEFORE the first- # connection so users get an actionable message instead of an opaque "attempt to write a readonly- # database" from deep inside _init_schema.if not read_only:return acquire(db_path)- def _needs_bootstrap() -> bool:- try:- return db_path.stat().st_size == 0- except FileNotFoundError:- return True- except OSError:- return False-- if _needs_bootstrap():- with _session_db_bootstrap_lock:- if _needs_bootstrap():- db = acquire(db_path)- release_or_close(db)-- def _open_probed():+ try:+ initialized = db_path.stat().st_size > 0+ except FileNotFoundError:+ initialized = False+ if not initialized:+ raise HTTPException(+ status_code=503,+ detail="Session store is not initialized. Start this profile's gateway to initialize it.")++ try:db = SessionDB(db_path=db_path, read_only=True)- # Unit-test fakes may replace SessionDB without exposing a raw- # connection. Probe only real connections.- conn = getattr(db, "_conn", None)- if conn is not None and str(db_path) not in _session_db_heal_exhausted:- try:+ try:+ conn = getattr(db, "_conn", None)+ if conn is not None:for statement in _session_db_read_probe_statements():conn.execute(statement).fetchone()- except BaseException:- db.close()- raise- return db-- try:- return _open_probed()- except (sqlite3.DatabaseError, UnicodeDecodeError) as exc:- # UnicodeDecodeError = pysqlite could not decode SQLite's own error- # message because corrupt file bytes were embedded in it; the- # one-writable-open heal is the only repair path, so treat it as- # malformed schema.- if not (- _is_stale_schema_error(exc)- or is_malformed_schema_error(exc)- or isinstance(exc, UnicodeDecodeError)):+ return db+ except BaseException:+ db.close()raise- db = acquire(db_path)- release_or_close(db)- try:- return _open_probed()- except (sqlite3.DatabaseError, UnicodeDecodeError) as still_stale:- if not _is_stale_schema_error(still_stale):- raise- # Writable open succeeded but the store is STILL behind the probe:- # serve reads without the probe (only queries touching the broken- # part fail) and stop paying the writable init per poll.- _session_db_heal_exhausted.add(str(db_path))- if str(db_path) not in _session_db_heal_warned:- _session_db_heal_warned.add(str(db_path))- _log.warning(- "state.db at %s is missing schema that a writable "- "reconcile could not add (%s); read paths may partially "- "fail until the store is repaired",- db_path,- still_stale)- return _open_probed()+ except (sqlite3.DatabaseError, UnicodeDecodeError) as exc:+ if isinstance(exc, sqlite3.OperationalError) and is_transient_sqlite_error(exc):+ detail = "Session store is busy (disk I/O or lock). Retry; the list was not cleared."+ else:+ detail = (+ "Session store schema is unavailable or corrupt. Start or restart this profile's "+ "gateway to reconcile it; if it persists, run `hermes doctor` for diagnosis. "+ "Browsing does not repair the store.")+ raise HTTPException(status_code=503, detail=detail) from excdef _open_session_db_for_profile(profile: Optional[str], *, read_only: bool):@@ -204,9 +144,11 @@ _last_auto_archive_check: Dict[str, float] = {}def _maybe_auto_archive_for_profile(profile: Optional[str]) -> None:- """Config-gated stale-session auto-archive for ``profile``; never raises.- ``hermes serve`` runs neither CLI nor gateway startup hooks, so this- session-list trigger is what makes ``sessions.auto_archive`` work there."""+ """Config-gated owner-lifetime maintenance, never invoked by browsing.++ The standalone serve ticker maintains its own profile; a composed HTTP+ listener relies on its gateway owner's startup and housekeeping hooks.+ """try:key = profile or ""now = time.monotonic()diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 46c89c37adf..0ea56443016 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -388,7 +388,7 @@ class TestWebServerEndpoints:assert seen["thread"] != event_loop_thread- def test_get_sessions_auto_archive_uses_maintenance_writer(self):+ def test_get_sessions_leaves_auto_archive_to_owner(self):from hermes_cli import web_serverfrom hermes_cli.config import load_config, save_configfrom hermes_constants import get_hermes_home@@ -420,25 +420,28 @@ class TestWebServerEndpoints:response = self.client.get("/api/sessions?limit=50&offset=0")assert response.status_code == 200- assert [row["id"] for row in response.json()["sessions"]] == ["fresh"]+ assert {row["id"] for row in response.json()["sessions"]} == {"fresh", "stale"}verify = SessionDB(db_path=db_path, read_only=True)try:- assert verify.get_session("stale")["archived"] == 1- assert verify.get_meta("last_auto_archive")+ assert verify.get_session("stale")["archived"] == 0+ assert not verify.get_meta("last_auto_archive")finally:verify.close()- def test_get_sessions_fresh_store_returns_empty_list(self):+ def test_get_sessions_missing_store_is_unavailable_without_creation(self):+ from hermes_constants import get_hermes_home++ before = set(get_hermes_home().glob("state.db*"))response = self.client.get("/api/sessions?limit=50&offset=0")- assert response.status_code == 200- assert response.json()["sessions"] == []- assert response.json()["total"] == 0+ assert response.status_code == 503+ assert "not initialized" in response.json()["detail"]+ assert set(get_hermes_home().glob("state.db*")) == before@pytest.mark.parametrize("missing_column", ["archived", "pinned", "last_activity_at"])- def test_get_sessions_heals_stale_schema_store(self, missing_column):+ def test_get_sessions_reports_stale_schema_without_healing(self, missing_column):import sqlite3from hermes_constants import get_hermes_home@@ -461,12 +464,12 @@ class TestWebServerEndpoints:finally:legacy.close()+ before = db_path.read_bytes()response = self.client.get("/api/sessions?limit=50&offset=0")- assert response.status_code == 200- assert [row["id"] for row in response.json()["sessions"]] == [- "stale-schema"- ]+ assert response.status_code == 503+ assert "schema" in response.json()["detail"]+ assert db_path.read_bytes() == beforehealed = sqlite3.connect(str(db_path))try:columns = {@@ -474,17 +477,10 @@ class TestWebServerEndpoints:}finally:healed.close()- assert missing_column in columns-- def test_profiles_sidebar_heals_stale_schema_store(self):- """The desktop's batched sidebar route must heal a stale store too.+ assert missing_column not in columns- The shipped regression (#72424 aftermath): a store predating- ``sessions.last_activity_at`` made every per-profile read raise- "no such column", which this endpoint swallowed into its ``errors``- array — the desktop rendered "No sessions yet" after `hermes update`- until the user's first message forced a writable open elsewhere.- """+ def test_profiles_sidebar_reports_stale_schema_store(self):+ """Aggregation reports unavailable profiles instead of healing their DBs."""import sqlite3from hermes_constants import get_hermes_home@@ -512,10 +508,9 @@ class TestWebServerEndpoints:assert response.status_code == 200payload = response.json()- assert payload["errors"] == []- assert [row["id"] for row in payload["recents"]["sessions"]] == [- "sidebar-stale"- ]+ assert payload["errors"]+ assert "schema" in payload["errors"][0]["error"]+ assert payload["recents"]["sessions"] == []def test_startup_eager_reconcile_heals_stale_store(self):"""The lifespan's eager reconcile brings a stale store current.@@ -578,71 +573,27 @@ class TestWebServerEndpoints:raise sqlite3_module.OperationalError("database is locked")monkeypatch.setattr(hermes_state, "SessionDB", boom)- # Must swallow — reads fall back to the per-poll probe heal.+ # Must swallow — reads report unavailable until owner recovery._web_server_lifecycle._eager_reconcile_own_session_db()- def test_heal_gives_up_when_reconcile_cannot_fix_the_store(self, monkeypatch):- """A probe failure reconciliation can't cure must not retry forever.-- The writable heal is a full SessionDB init against a possibly-live- DB. If the store is STILL behind the probe afterwards (schema problem- ADD COLUMN can't express), retrying that init on every sidebar poll- would hammer the DB for nothing: serve reads probe-less instead, warn- once, and never pay the writable open for that store again.- """- from hermes_cli import web_server+ def test_failed_schema_probes_never_escalate_reads(self, monkeypatch):+ from fastapi import HTTPExceptionfrom hermes_constants import get_hermes_homefrom hermes_state import SessionDBdb_path = get_hermes_home() / "state.db"seed = SessionDB(db_path=db_path)- try:- seed.create_session("unfixable", source="cli")- finally:- seed.close()-- # A column no SCHEMA_SQL declares: the heal's writable reconcile- # cannot add it, so the re-probe keeps failing.+ seed.create_session("unfixable", source="cli")+ seed.close()monkeypatch.setattr(- _web_server_sessions,- "_session_db_read_probe_statements",- lambda: ('SELECT "sessions"."not_a_real_column" FROM "sessions" LIMIT 0',),- )- monkeypatch.setattr(_web_server_sessions, "_session_db_heal_exhausted", set())- monkeypatch.setattr(_web_server_sessions, "_session_db_heal_warned", set())-- writable_opens = []-- import hermes_state-- original_init = hermes_state.SessionDB.__init__-- def counting_init(self, *args, **kwargs):- if not kwargs.get("read_only", False):- writable_opens.append(1)- return original_init(self, *args, **kwargs)-- # web_server imports SessionDB inside the function body, so patching- # the class on hermes_state covers every open the helper makes.- monkeypatch.setattr(hermes_state.SessionDB, "__init__", counting_init)-- # First open: probe fails -> one writable heal -> re-probe fails ->- # exhausted. Still returns a usable read-only handle.- db = _web_server_sessions._open_session_db_for_profile(None, read_only=True)- try:- assert db.list_sessions_rich(limit=10, compact_rows=True)- finally:- db.close()- assert len(writable_opens) == 1- assert str(db_path) in _web_server_sessions._session_db_heal_exhausted-- # Second open: probe skipped, NO further writable opens.- db = _web_server_sessions._open_session_db_for_profile(None, read_only=True)- try:- assert db.list_sessions_rich(limit=10, compact_rows=True)- finally:- db.close()- assert len(writable_opens) == 1+ _web_server_sessions, "_session_db_read_probe_statements",+ lambda: ('SELECT "sessions"."not_a_real_column" FROM "sessions" LIMIT 0',))+ before = db_path.read_bytes()+ for _ in range(2):+ with pytest.raises(HTTPException, match="schema") as caught:+ _web_server_sessions._open_session_db_for_profile(None, read_only=True)+ assert caught.value.status_code == 503+ assert db_path.read_bytes() == beforedef test_generic_corruption_does_not_trigger_writable_heal(self, tmp_path, monkeypatch@@ -663,42 +614,30 @@ class TestWebServerEndpoints:monkeypatch.setattr(hermes_state, "SessionDB", corrupt_open)- with pytest.raises(sqlite3.DatabaseError, match="disk image is malformed"):+ from fastapi import HTTPException+ with pytest.raises(HTTPException, match="corrupt"):_web_server_sessions._open_session_db_at_path(db_path, read_only=True)assert opens == [True]- def test_decode_error_triggers_writable_heal(self, tmp_path, monkeypatch):- """UnicodeDecodeError — pysqlite failing to decode SQLite's own error- message over corrupt file bytes (#98924) — must route through the- same one-writable-open heal as malformed schema."""+ def test_decode_error_never_triggers_writable_heal(self, tmp_path, monkeypatch):import hermes_state- from hermes_cli import web_server+ from fastapi import HTTPExceptiondb_path = tmp_path / "state.db"db_path.write_bytes(b"not-empty")opens = []- class _OkDB:- _conn = None-- def close(self):- pass-- def scripted_open(*_args, **kwargs):+ def corrupt_open(*_args, **kwargs):opens.append(kwargs.get("read_only", False))- if opens == [True]:- raise UnicodeDecodeError("utf-8", b"\x81", 0, 1, "invalid start byte")- return _OkDB()-- monkeypatch.setattr(hermes_state, "SessionDB", scripted_open)+ raise UnicodeDecodeError("utf-8", b"\x81", 0, 1, "invalid start byte")- db = _web_server_sessions._open_session_db_at_path(db_path, read_only=True)-- assert isinstance(db, _OkDB)- assert opens == [True, False, True]+ monkeypatch.setattr(hermes_state, "SessionDB", corrupt_open)+ with pytest.raises(HTTPException, match="corrupt"):+ _web_server_sessions._open_session_db_at_path(db_path, read_only=True)+ assert opens == [True]- def test_get_sessions_zero_byte_store_returns_empty_list(self):+ def test_get_sessions_zero_byte_store_is_not_quarantined(self):from hermes_constants import get_hermes_homedb_path = get_hermes_home() / "state.db"@@ -707,11 +646,11 @@ class TestWebServerEndpoints:response = self.client.get("/api/sessions?limit=50&offset=0")- assert response.status_code == 200- assert response.json()["sessions"] == []- assert response.json()["total"] == 0+ assert response.status_code == 503+ assert db_path.read_bytes() == b""+ assert set(db_path.parent.glob("state.db*")) == {db_path}- def test_concurrent_first_load_reads_all_succeed_on_fresh_store(self):+ def test_concurrent_first_load_reads_report_uninitialized_store(self):from concurrent.futures import ThreadPoolExecutorpaths = [@@ -723,9 +662,7 @@ class TestWebServerEndpoints:with ThreadPoolExecutor(max_workers=8) as pool:responses = list(pool.map(self.client.get, paths))- assert [response.status_code for response in responses] == [- 200- ] * len(paths)+ assert [response.status_code for response in responses] == [503] * len(paths)diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex 23cdb2b412a..4c2f91dd0ac 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -204,6 +204,25 @@ background FTS rebuild can proceed without double-indexing) and cover all threeindexed columns — see `SCHEMA_SQL` in `hermes_state_common.py` for the exact SQL.+## Dashboard browsing and owner maintenance++Session browsing opens `state.db` read-only. GET listing, search, details,+messages, statistics and export never create an absent database, quarantine a+zero-byte file, reconcile a stale schema, or trigger auto-archive. Uninitialized+or incompatible stores return HTTP 503 with owner-start/recovery guidance;+profile aggregation reports schema failures in its per-profile `errors` list.++The profile's gateway initializes and reconciles its store at startup. The+standalone `serve` backend retains its existing startup reconciliation worker.+Configured `sessions.auto_archive` remains active through gateway startup and+housekeeping, or the standalone backend's maintenance ticker, independently of+browsing. Explicit mutation endpoints retain their existing write behavior.++SQLite WAL readers still participate in shared-memory coordination: `mode=ro`+may create empty WAL/SHM sidecars or update SHM read marks. The read-only contract+forbids canonical schema/data writes, repair and checkpointing; it does not make+live SQLite coordination files immutable.+## Schema Version and MigrationsCurrent schema version: **23**