Skip to content

The agent that grows with you

fix(state): recover from read-only database files at startup

Teknium373632e33813
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index a4b3c383df7..ca81157decb 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -2150,6 +2150,12 @@ def connect(
return conn
with _cross_process_init_lock(path):
+ # Read-only file/sidecar preflight (port of kilocode#12508) —
+ # repair-or-refuse before the header/integrity probes so a stray
+ # read-only kanban.db fails with an actionable message instead of
+ # "attempt to write a readonly database" mid-init.
+ from hermes_state import preflight_db_writability
+ preflight_db_writability(path, db_label=f"kanban.db ({path.name})")
# Cheap byte-level check first — catches the #29507 TLS-overwrite shape
# and other invalid-header cases without opening a sqlite connection.
_validate_sqlite_header(path)
diff --git a/hermes_state.py b/hermes_state.py
index f309acce127..73fa3580a2a 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -846,6 +846,96 @@ def _backup_db_file(db_path: Path) -> Optional[Path]:
return None
+def preflight_db_writability(
+ db_path: Path,
+ *,
+ db_label: str = "state.db",
+) -> None:
+ """Refuse-or-repair read-only DB files BEFORE the first connection opens.
+
+ Port of Kilo-Org/kilocode#12508's startup preflight. A stray read-only
+ ``state.db`` / ``-wal`` / ``-shm`` (sudo run, restored backup, copied
+ dotfiles) previously surfaced as an opaque
+ ``sqlite3.OperationalError: attempt to write a readonly database`` raised
+ from deep inside ``_init_schema`` — naming no file and no fix — and the
+ obvious wrong "fix" (deleting the ``-wal``) silently loses committed
+ transactions. This preflight:
+
+ - **Repairs** permissions with ``chmod u+rw`` when the file lives inside
+ the Hermes home tree (``get_hermes_home()``) — the safe repair scope:
+ Hermes owns those files, and the OS makes ``chmod`` fail on files the
+ user doesn't own, which bounds the repair exactly.
+ - **Fails fast with an actionable error** naming the exact file and the
+ exact ``chmod`` command for anything else (root-owned files, read-only
+ mounts, custom paths outside the home tree).
+ - Never deletes or truncates a WAL sidecar — once writable, the normal
+ open path checkpoints its committed frames into the DB as intended.
+
+ ``:memory:`` and ``file:`` URI paths are skipped (no plain on-disk files
+ to check). Shared by :class:`SessionDB` and ``hermes_cli.kanban_db``.
+ """
+ raw = str(db_path)
+ if raw == ":memory:" or raw.startswith("file:"):
+ return
+
+ try:
+ home: Optional[Path] = Path(get_hermes_home()).resolve()
+ except Exception: # pragma: no cover - defensive
+ home = None
+
+ def _in_repair_scope(p: Path) -> bool:
+ if home is None:
+ return False
+ try:
+ return p.resolve().is_relative_to(home)
+ except (OSError, ValueError):
+ return False
+
+ def _ensure_writable(p: Path, *, is_dir: bool = False) -> None:
+ import stat as _stat
+
+ if os.access(p, os.R_OK | os.W_OK):
+ return
+ if _in_repair_scope(p):
+ try:
+ add = _stat.S_IRUSR | _stat.S_IWUSR | (_stat.S_IXUSR if is_dir else 0)
+ os.chmod(p, p.stat().st_mode | add)
+ except OSError:
+ pass
+ if os.access(p, os.R_OK | os.W_OK):
+ logger.info(
+ "%s preflight: repaired read-only %s (chmod u+rw%s)",
+ db_label,
+ p,
+ "x" if is_dir else "",
+ )
+ return
+ kind = "directory" if is_dir else "file"
+ wal_note = (
+ " Do NOT delete the -wal file — it contains committed data that "
+ "will be merged into the database once it is writable."
+ if p.name.endswith("-wal")
+ else ""
+ )
+ raise sqlite3.OperationalError(
+ f"{db_label} is not writable: {kind} {p} is read-only for this "
+ f"user. Hermes needs read-write access to open the database. "
+ f"Fix with: chmod u+rw{'x' if is_dir else ''} '{p}'"
+ f" (files owned by another user may need sudo/chown).{wal_note}"
+ )
+
+ parent = db_path.parent
+ if parent.is_dir():
+ # SQLite needs a writable directory in every journal mode (WAL and
+ # SHM sidecars in WAL mode; the rollback journal in DELETE mode).
+ _ensure_writable(parent, is_dir=True)
+
+ for suffix in ("", "-wal", "-shm"):
+ p = db_path.with_name(db_path.name + suffix) if suffix else db_path
+ if p.is_file():
+ _ensure_writable(p)
+
+
def _db_opens_cleanly(db_path: Path) -> Optional[str]:
"""Probe a DB on a fresh connection. Returns None if healthy, else a reason.
@@ -1948,6 +2038,13 @@ class SessionDB:
self.db_path.parent.mkdir(parents=True, exist_ok=True)
+ # 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:
+ preflight_db_writability(self.db_path, db_label="state.db")
+
# #68474: zeroed state.db (size>0, all-NUL header) used to fail as a
# generic "file is not a database" with no recovery path. Quarantine
# the bytes (do not delete) and continue so a fresh DB can open;
diff --git a/tests/test_hermes_state_readonly_preflight.py b/tests/test_hermes_state_readonly_preflight.py
new file mode 100644
index 00000000000..074a4002d8e
--- /dev/null
+++ b/tests/test_hermes_state_readonly_preflight.py
@@ -0,0 +1,214 @@
+"""Tests for the read-only DB preflight (port of Kilo-Org/kilocode#12508).
+
+A stray read-only ``state.db`` / ``-wal`` / ``-shm`` (sudo run, restored
+backup, copied dotfiles) used to surface as an opaque
+``sqlite3.OperationalError: attempt to write a readonly database`` raised
+from deep inside ``_init_schema`` — naming no file and no fix.
+
+``preflight_db_writability`` now runs before the first connection:
+
+- files inside the Hermes home tree are repaired with ``chmod u+rw``
+ (the safe scope — chmod fails on files the user doesn't own);
+- anything else fails fast with an error naming the exact file and the
+ exact ``chmod`` command;
+- WAL sidecars are never deleted, so committed frames survive repair.
+"""
+
+import os
+import sqlite3
+import stat
+import sys
+from pathlib import Path
+
+import pytest
+
+import hermes_state
+from hermes_state import SessionDB, preflight_db_writability
+
+pytestmark = [
+ pytest.mark.skipif(sys.platform == "win32", reason="POSIX chmod semantics"),
+ pytest.mark.skipif(
+ hasattr(os, "geteuid") and os.geteuid() == 0,
+ reason="root bypasses file permission checks",
+ ),
+]
+
+
+def hermes_home(tmp_path, monkeypatch):
+ """Isolated HERMES_HOME so the repair scope covers tmp DBs."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+def _make_db(path: Path) -> None:
+ conn = sqlite3.connect(str(path))
+ conn.execute("CREATE TABLE t (x)")
+ conn.execute("INSERT INTO t VALUES (1)")
+ conn.commit()
+ conn.close()
+
+
+def _make_wal_db(path: Path) -> None:
+ """Create a WAL-mode DB with committed-but-uncheckpointed frames."""
+ conn = sqlite3.connect(str(path))
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("CREATE TABLE t (x)")
+ conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ # Keep a READ-ONLY second connection open so neither close can
+ # checkpoint: the writer skips checkpoint-on-close because another
+ # connection exists, and the ro holder cannot checkpoint at all.
+ # The committed row therefore lives only in the -wal file.
+ holder = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ holder.execute("SELECT 1").fetchone()
+ conn.execute("INSERT INTO t VALUES (42)")
+ conn.commit()
+ conn.close()
+ holder.close()
+ assert path.with_name(path.name + "-wal").is_file(), (
+ "fixture precondition: -wal sidecar must survive with pending frames"
+ )
+
+
+class TestRepairScope:
+ def test_repairs_readonly_db_inside_home(self, hermes_home):
+ db = hermes_home / "state.db"
+ _make_db(db)
+ os.chmod(db, 0o444)
+
+ preflight_db_writability(db, db_label="state.db")
+
+ assert os.access(db, os.W_OK)
+
+ def test_repairs_readonly_sidecars(self, hermes_home):
+ db = hermes_home / "state.db"
+ _make_wal_db(db)
+ wal = db.with_name(db.name + "-wal")
+ assert wal.is_file(), "fixture must leave a -wal behind"
+ os.chmod(db, 0o444)
+ os.chmod(wal, 0o444)
+
+ preflight_db_writability(db, db_label="state.db")
+
+ assert os.access(db, os.W_OK)
+ assert os.access(wal, os.W_OK)
+
+ def test_wal_data_survives_repair(self, hermes_home):
+ """The committed WAL frame must be readable after repair — proof the
+ preflight never drops/truncates a sidecar."""
+ db = hermes_home / "state.db"
+ _make_wal_db(db)
+ wal = db.with_name(db.name + "-wal")
+ os.chmod(db, 0o444)
+ os.chmod(wal, 0o444)
+
+ preflight_db_writability(db, db_label="state.db")
+
+ conn = sqlite3.connect(str(db))
+ rows = conn.execute("SELECT x FROM t").fetchall()
+ conn.close()
+ assert (42,) in rows
+
+ def test_repairs_readonly_parent_directory(self, hermes_home):
+ sub = hermes_home / "kanban"
+ sub.mkdir()
+ db = sub / "kanban.db"
+ _make_db(db)
+ os.chmod(sub, 0o555)
+ try:
+ preflight_db_writability(db, db_label="kanban.db")
+ assert os.access(sub, os.W_OK)
+ finally:
+ os.chmod(sub, 0o755)
+
+
+class TestRefusalOutsideScope:
+ def test_actionable_error_names_file_and_chmod(self, hermes_home, tmp_path):
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ db = outside / "custom.db"
+ _make_db(db)
+ os.chmod(db, 0o444)
+ try:
+ with pytest.raises(sqlite3.OperationalError) as exc_info:
+ preflight_db_writability(db, db_label="custom.db")
+ msg = str(exc_info.value)
+ assert str(db) in msg
+ assert "chmod u+rw" in msg
+ # Must NOT have silently chmod'd a file outside the home tree.
+ assert not os.access(db, os.W_OK)
+ finally:
+ os.chmod(db, 0o644)
+
+ def test_wal_error_warns_against_deletion(self, hermes_home, tmp_path):
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ db = outside / "custom.db"
+ _make_wal_db(db)
+ wal = db.with_name(db.name + "-wal")
+ os.chmod(wal, 0o444)
+ try:
+ with pytest.raises(sqlite3.OperationalError) as exc_info:
+ preflight_db_writability(db, db_label="custom.db")
+ msg = str(exc_info.value)
+ assert str(wal) in msg
+ assert "Do NOT delete" in msg
+ finally:
+ os.chmod(wal, 0o644)
+
+
+class TestSkips:
+ def test_memory_uri_skipped(self, hermes_home):
+ preflight_db_writability(Path(":memory:"))
+
+ def test_file_uri_skipped(self, hermes_home):
+ preflight_db_writability(Path("file:whatever?mode=ro"))
+
+ def test_missing_files_no_error(self, hermes_home):
+ preflight_db_writability(hermes_home / "state.db")
+
+ def test_healthy_db_untouched(self, hermes_home):
+ db = hermes_home / "state.db"
+ _make_db(db)
+ before = stat.S_IMODE(db.stat().st_mode)
+ preflight_db_writability(db)
+ assert stat.S_IMODE(db.stat().st_mode) == before
+
+
+class TestSessionDBIntegration:
+ def test_sessiondb_selfheals_readonly_db_in_home(self, hermes_home):
+ db_path = hermes_home / "state.db"
+ first = SessionDB(db_path)
+ first.close()
+ for suffix in ("", "-wal", "-shm"):
+ p = db_path.with_name(db_path.name + suffix)
+ if p.is_file():
+ os.chmod(p, 0o444)
+
+ db = SessionDB(db_path) # must not raise "readonly database"
+ try:
+ assert os.access(db_path, os.W_OK)
+ finally:
+ db.close()
+
+ def test_sessiondb_actionable_error_outside_home(
+ self, hermes_home, tmp_path
+ ):
+ outside = tmp_path / "custom-loc"
+ outside.mkdir()
+ db_path = outside / "state.db"
+ first = SessionDB(db_path)
+ first.close()
+ os.chmod(db_path, 0o444)
+ hermes_state._set_last_init_error(None)
+ try:
+ with pytest.raises(sqlite3.OperationalError) as exc_info:
+ SessionDB(db_path)
+ msg = str(exc_info.value)
+ assert str(db_path) in msg
+ assert "chmod" in msg
+ finally:
+ os.chmod(db_path, 0o644)
+ hermes_state._set_last_init_error(None)