The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(recovery): stop pointing sqlite3 .recover guidance at the live state.db
sal5d9a2110badd
diff --git a/gateway/run.py b/gateway/run.pyindex 36f7cf75eed..13f12a2e5a6 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -27485,8 +27485,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"⚠️ Session database corruption detected. Messages may not be ""persisted. Recovery options:\n""1. Run `hermes doctor --fix`\n"- "2. Salvage with: sqlite3 ~/.hermes/state.db \".recover\" "- "(then replace state.db)\n"+ "2. Recover with: `hermes sessions recover --source "+ "~/.hermes/state.db` (it snapshots the damaged file first — "+ "do NOT run `sqlite3 ... \".recover\"` against the live "+ "state.db, a vulnerable sqlite3 CLI can corrupt it further)\n""3. Restore from a backup in ~/.hermes/backups/\n""Run `hermes doctor` for sanitized diagnostics.")diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.pyindex 7037941a465..8cef5141b21 100644--- a/hermes_cli/kanban.py+++ b/hermes_cli/kanban.py@@ -3451,8 +3451,10 @@ def _cmd_repair(args: argparse.Namespace) -> int:print(f" corrupt copy quarantined at: {report.backup_path}",file=sys.stderr)print(- " Recover manually (e.g. `sqlite3 kanban.db \".recover\"` into a "- "fresh file) or move the file aside to start a new board.",+ " Recover manually (copy kanban.db aside FIRST, then run "+ "`sqlite3 <copy> \".recover\"` into a fresh file — never against "+ "the live path, a WAL-reset-vulnerable sqlite3 CLI can corrupt it "+ "further) or move the file aside to start a new board.",file=sys.stderr,)return 1diff --git a/hermes_cli/session_lost_and_found.py b/hermes_cli/session_lost_and_found.pyindex 96c4d203c29..cb1622783a5 100644--- a/hermes_cli/session_lost_and_found.py+++ b/hermes_cli/session_lost_and_found.py@@ -23,6 +23,7 @@ data, and derived FTS indexes are rebuilt from scratch.from __future__ import annotations+import loggingimport reimport shutilimport sqlite3@@ -31,7 +32,7 @@ import tempfilefrom pathlib import Pathfrom typing import Any, Optional-# Hermes session ids are timestamps: 20260812_135332_ab12cd. This is the+logger = logging.getLogger(__name__)# Hermes session ids are timestamps: 20260812_135332_ab12cd. This is the# strongest sentinel available for classifying schema-less rows.SESSION_ID_PATTERN = re.compile(r"^\d{8}_\d{6}_")@@ -72,25 +73,122 @@ SQLITE3_CLI_GUIDANCE = ("with --allow-partial.")+# SQLite's WAL-reset bug (https://sqlite.org/wal.html#walresetbug) lets a+# fresh opener unlink a live WAL/SHM sidecar pair and split the database into+# two concurrent generations whose acknowledged writes can silently vanish.+# It is real in CLI builds up to 3.51.2; fixed in 3.51.3+ with backports+# 3.50.7 and 3.44.6 — the same version gate hermes_state applies to the+# embedded library (#69784). The system `sqlite3` CLI on Debian/Ubuntu is+# routinely in the vulnerable band (e.g. 3.45.1), and #100368's forensics+# caught exactly this shell converting a live Hermes state.db into two+# generations. A salvage shell must therefore be version-gated, not just+# capability-gated, before it is pointed at (a copy of) a Hermes database.+#+# The predicate lives in hermes_cli.sqlite_runtime (stdlib-only, shared with+# the installer/update gates) so the embedded runtime and the salvage shell+# can never disagree about which versions are safe.+from hermes_cli.sqlite_runtime import is_sqlite_wal_reset_vulnerable as _wal_reset_vulnerable # noqa: E502++_WAL_RESET_VULNERABLE_GUIDANCE = (+ "salvage against a Hermes database with the WAL-reset bug "+ "(https://sqlite.org/wal.html#walresetbug, fixed in 3.51.3+ / backports "+ "3.50.7 / 3.44.6; the vulnerable fresh-opener can unlink a live WAL/SHM "+ "pair and split the database into two generations, losing acknowledged "+ "writes — #100368). Install a fixed sqlite3 CLI (3.51.3+, e.g. `brew "+ "install sqlite` or the precompiled sqlite-tools from sqlite.org)"+)+class LostAndFoundError(RuntimeError):"""Raised when the CLI .recover pass cannot produce a usable database."""-def find_sqlite3_cli() -> Optional[str]:- """Return a ``.recover``-capable sqlite3 CLI path, or None.+def _parse_sqlite3_cli_version(binary: str) -> Optional[tuple[int, int, int]]:+ """Parse the reporting version of the sqlite3 CLI at *binary*.++ Returns ``None`` when the CLI cannot be executed or its version line+ cannot be understood (older shells print the version only in+ interactive mode; the modern ``--version`` flag covers every build in+ the supported range).+ """+ try:+ probe = subprocess.run(+ [binary, "--version"],+ capture_output=True,+ timeout=30,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if probe.returncode != 0:+ return None+ match = re.search(rb"(\d+)\.(\d+)\.(\d+)", probe.stdout)+ if match is None:+ return None+ return tuple(int(part) for part in match.groups())+++_last_cli_refusal: dict[str, Any] = {}- PATH presence is not enough: distro builds (e.g. Ubuntu's) can ship a- sqlite3 shell compiled without the ``sqlite_dbpage`` virtual table that- ``.recover`` requires — those fail every recovery with- ``no such table: sqlite_dbpage``. Probe capability on a scratch DB once- instead of discovering it mid-recovery.++def find_sqlite3_cli_refusal() -> dict[str, Any]:+ """Why the last :func:`find_sqlite3_cli` call in this process refused.++ ``{"reason": ...}`` with ``reason`` in ``missing``, ``no_dbpage`` (the+ shell cannot run ``.recover``), or ``wal_reset_vulnerable``; empty when+ the last probe found a usable shell or never ran."""+ return dict(_last_cli_refusal)++def find_sqlite3_cli() -> Optional[str]:+ """Return a salvage-safe ``.recover``-capable sqlite3 CLI path, or None.++ PATH presence is not enough, and neither is `.recover` support alone:++ 1. Distro builds (e.g. Ubuntu's) can ship a sqlite3 shell compiled+ without the ``sqlite_dbpage`` virtual table that ``.recover``+ requires — those fail every recovery with ``no such table:+ sqlite_dbpage``. Capability is probed on a scratch DB once.+ 2. A `.recover`-capable CLI can still carry the WAL-reset opener bug+ (fixed 3.51.3+ / backports 3.50.7 / 3.44.6). The salvage lane runs+ the CLI against a *snapshot copy* of the source, so it cannot hit+ the live sidecars itself; but the same binary is what operators+ reach for when following the old guidance, and refusing it here+ keeps the vulnerable shells out of the documented workflow+ entirely. Probe the version once.++ Refusals are recorded for :func:`find_sqlite3_cli_refusal` so callers+ can explain exactly what to install instead of a generic "not found".+ """+ global _last_cli_refusal+ _last_cli_refusal = {}binary = shutil.which("sqlite3")if binary is None:+ _last_cli_refusal = {"reason": "missing"}+ return None+ if not _cli_supports_recover(binary):+ _last_cli_refusal = {"reason": "no_dbpage", "binary": binary}+ return None+ version = _parse_sqlite3_cli_version(binary)+ if version is not None and _wal_reset_vulnerable(version):+ version_str = ".".join(str(part) for part in version)+ logger.warning(+ "sqlite3 CLI %s reports version %s, which still carries the "+ "WAL-reset opener bug; refusing to use it for salvage",+ binary,+ version_str,+ )+ _last_cli_refusal = {+ "reason": "wal_reset_vulnerable",+ "binary": binary,+ "version": version_str,+ "detail": (+ f"reports version {version_str}, which has "+ + _WAL_RESET_VULNERABLE_GUIDANCE+ ),+ }return None- return binary if _cli_supports_recover(binary) else None+ return binarydef _cli_supports_recover(binary: str) -> bool:diff --git a/hermes_cli/session_recovery.py b/hermes_cli/session_recovery.pyindex c5228e2cf38..14ea0bfff99 100644--- a/hermes_cli/session_recovery.py+++ b/hermes_cli/session_recovery.py@@ -1496,6 +1496,7 @@ def _recover_via_lost_and_found(SQLITE3_CLI_GUIDANCE,LostAndFoundError,find_sqlite3_cli,+ find_sqlite3_cli_refusal,map_lost_and_found_rows,rebuild_fts_indexes,run_cli_lost_and_found_recover,@@ -1504,6 +1505,16 @@ def _recover_via_lost_and_found(sqlite3_bin = find_sqlite3_cli()if sqlite3_bin is None:+ refusal = find_sqlite3_cli_refusal()+ if refusal.get("reason") == "wal_reset_vulnerable":+ raise SessionRecoverySourceError(+ "Partial recovery requires a page-level salvage shell, but "+ "the only sqlite3 CLI on PATH is not safe to use for it: it "+ + refusal["detail"]+ + ". The readable table schemas for: "+ + ", ".join(missing_required)+ + " are still required."+ )raise SessionRecoverySourceError("Partial recovery still requires readable table schemas for: "+ ", ".join(missing_required)diff --git a/hermes_state.py b/hermes_state.pyindex d80326c523c..cbe66be1be2 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -2906,7 +2906,10 @@ def _persistent_repair_exhausted_error(db_path: Path) -> str:f"{_MAX_PERSISTENT_REPAIR_ATTEMPTS} times on this exact file — ""the corruption is beyond the schema/FTS repair strategies ""(likely b-tree page damage). Manual recovery required: restore "- f"a backup, or salvage with `sqlite3 {db_path} \".recover\"`. "+ "a backup, or salvage with `hermes sessions recover --source "+ f"{db_path}` (it snapshots the damaged file first, then runs the "+ "page-level `.recover` lane on the copy; do NOT point a raw "+ "`sqlite3` shell at the live database). "f"Delete {_repair_ledger_path(db_path).name} to force another ""automatic attempt.")@@ -3105,8 +3108,8 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":f"only {usage.free / 1e9:.2f}GB free on {db_path.parent}; "f"copying the damaged DB needs {need / 1e9:.2f}GB and must "f"leave {headroom / 1e9:.2f}GB headroom. Free disk space, "- f"then retry (or recover manually with `sqlite3 {db_path} "- '".recover"`).'+ "then retry (or recover manually with "+ f"`hermes sessions recover --source {db_path}`).")logger.error("Refusing forensic backup of %s: %s", db_path, reason)return None, reason@@ -3120,7 +3123,7 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":f"could not determine free space on {db_path.parent} ({exc}); ""refusing the forensic copy rather than risk filling the "f"volume. Free disk space, then retry (or recover manually "- f'with `sqlite3 {db_path} ".recover"`).'+ f"with `hermes sessions recover --source {db_path}`).")logger.error("Refusing forensic backup of %s: %s", db_path, reason)return None, reasondiff --git a/run_agent.py b/run_agent.pyindex 36721ad38b7..b17f352ccc1 100644--- a/run_agent.py+++ b/run_agent.py@@ -4430,8 +4430,11 @@ class AIAgent:"have been lost on restart). Freeing disk space will ""not help. Recovery options:\n""1. Run `hermes doctor --fix`\n"- "2. Salvage with: sqlite3 ~/.hermes/state.db \".recover\" "- "(then replace state.db)\n"+ "2. Recover with: `hermes sessions recover --source "+ "~/.hermes/state.db` (it snapshots the damaged file "+ "first — do NOT run `sqlite3 ... \".recover\"` against "+ "the live state.db, a vulnerable sqlite3 CLI can "+ "corrupt it further)\n""3. Restore from a backup in ~/.hermes/backups/\n""Then send your message again.")diff --git a/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.pynew file mode 100644index 00000000000..36dfd60ab3a--- /dev/null+++ b/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py@@ -0,0 +1,248 @@+"""#100368 regression: the corruption guidance must not direct a WAL-reset-+vulnerable sqlite3 CLI at a live Hermes database.++Field forensics (issue #100368, maintainer round 2 + the isolated reproducer+in its comments): when a shell with SQLite's WAL-reset opener bug (fixed+3.51.3+ / backports 3.50.7 / 3.44.6 — Debian/Ubuntu system CLIs 3.45.1 /+3.46.1 are in the vulnerable band) opens a live state.db whose writer's DMS+lock has been cancelled, it unlinks the live -wal/-shm pair and splits the+store into two concurrent generations. Both generations report+``integrity_check ok`` while an old-generation acknowledged write is lost.++Hermes' own corruption banners used to instruct exactly that command+(`sqlite3 ~/.hermes/state.db ".recover"`). The fix routes operators to+`hermes sessions recover --source ...`, whose lane snapshots the damaged+bundle before any shell touches it, and refuses a WAL-reset-vulnerable+sqlite3 CLI for the page-level salvage lane even on the snapshot.+"""++from __future__ import annotations++import inspect+from pathlib import Path+from unittest.mock import patch++import pytest++from hermes_cli.session_lost_and_found import (+ _parse_sqlite3_cli_version,+ _wal_reset_vulnerable,+ find_sqlite3_cli,+ find_sqlite3_cli_refusal,+)+from hermes_cli.sqlite_runtime import is_sqlite_wal_reset_vulnerable+++LIVE_DB_SALVAGE_COMMAND = 'sqlite3 ~/.hermes/state.db ".recover"'+++# ---------------------------------------------------------------------------+# The version gate itself+# ---------------------------------------------------------------------------+++class TestWalResetVersionGate:+ @pytest.mark.parametrize(+ "version",+ [(3, 45, 1), (3, 46, 1), (3, 44, 5), (3, 50, 4), (3, 51, 2), (3, 8, 0)],+ )+ def test_vulnerable_versions(self, version):+ assert _wal_reset_vulnerable(version) is True++ @pytest.mark.parametrize(+ "version",+ [+ (3, 44, 6),+ (3, 44, 7),+ (3, 50, 7),+ (3, 50, 8),+ (3, 51, 3),+ (3, 51, 4),+ (3, 52, 0),+ (3, 53, 1),+ (4, 0, 0),+ ],+ )+ def test_fixed_versions(self, version):+ assert _wal_reset_vulnerable(version) is False++ def test_gate_mirrors_library_gate(self):+ """The salvage gate must agree with the shared runtime gate so the+ embedded library and the salvage shell can never disagree."""+ versions = [+ (3, 44, 5),+ (3, 44, 6),+ (3, 45, 1),+ (3, 50, 4),+ (3, 50, 7),+ (3, 51, 2),+ (3, 51, 3),+ (3, 53, 1),+ ]+ for version in versions:+ assert _wal_reset_vulnerable(version) == (+ is_sqlite_wal_reset_vulnerable(version)+ ), f"salvage gate disagrees with the runtime gate at {version}"+++# ---------------------------------------------------------------------------+# find_sqlite3_cli refuses unsafe shells and explains why+# ---------------------------------------------------------------------------+++class TestFindSqlite3CliRefusal:+ def test_missing_binary_refusal(self, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found.shutil.which", lambda _: None+ )+ assert find_sqlite3_cli() is None+ assert find_sqlite3_cli_refusal()["reason"] == "missing"++ def test_no_dbpage_refusal(self, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found.shutil.which",+ lambda _: "/usr/bin/sqlite3",+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._cli_supports_recover",+ lambda _: False,+ )+ assert find_sqlite3_cli() is None+ assert find_sqlite3_cli_refusal()["reason"] == "no_dbpage"++ def test_wal_reset_vulnerable_refusal(self, monkeypatch):+ """A .recover-capable but WAL-reset-vulnerable CLI must be refused.++ This is the Debian/Ubuntu shape from the #100368 incident: the+ system sqlite3 (3.45.1) has sqlite_dbpage, so the capability probe+ passes, while the WAL-reset opener bug is still present.+ """+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found.shutil.which",+ lambda _: "/usr/bin/sqlite3",+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._cli_supports_recover",+ lambda _: True,+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",+ lambda _: (3, 45, 1),+ )+ assert find_sqlite3_cli() is None+ refusal = find_sqlite3_cli_refusal()+ assert refusal["reason"] == "wal_reset_vulnerable"+ assert refusal["version"] == "3.45.1"+ assert "WAL-reset" in refusal["detail"]++ def test_fixed_capable_cli_accepted(self, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found.shutil.which",+ lambda _: "/usr/local/bin/sqlite3",+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._cli_supports_recover",+ lambda _: True,+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",+ lambda _: (3, 51, 3),+ )+ assert find_sqlite3_cli() == "/usr/local/bin/sqlite3"+ assert find_sqlite3_cli_refusal() == {}++ def test_unparsable_version_still_usable(self, monkeypatch):+ """A CLI whose version line cannot be parsed is not refused on+ version grounds alone (the salvage lane runs against a snapshot+ copy, not the live file)."""+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found.shutil.which",+ lambda _: "/usr/bin/sqlite3",+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._cli_supports_recover",+ lambda _: True,+ )+ monkeypatch.setattr(+ "hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",+ lambda _: None,+ )+ assert find_sqlite3_cli() == "/usr/bin/sqlite3"+++class TestParseSqlite3CliVersion:+ def test_parses_modern_output(self):+ class Probe:+ returncode = 0+ stdout = b"3.51.4 2026-XX-XX 12:34:56\n"++ with patch(+ "hermes_cli.session_lost_and_found.subprocess.run",+ return_value=Probe(),+ ):+ assert _parse_sqlite3_cli_version("x") == (3, 51, 4)++ def test_unexecutable_returns_none(self):+ with patch(+ "hermes_cli.session_lost_and_found.subprocess.run",+ side_effect=OSError("no such file"),+ ):+ assert _parse_sqlite3_cli_version("x") is None+++# ---------------------------------------------------------------------------+# The operator-facing guidance never names the live DB+# ---------------------------------------------------------------------------+++class TestGuidanceNeverNamesLiveDb:+ def test_gateway_corruption_banner(self):+ """The gateway broadcast must route to `sessions recover` and must+ warn against pointing a raw sqlite3 shell at the live file."""+ import gateway.run as gateway_run++ body = inspect.getsource(+ gateway_run.GatewayRunner._send_session_db_warning_notifications+ )+ assert LIVE_DB_SALVAGE_COMMAND not in body+ assert "sessions recover --source" in body+ assert "do NOT" in body++ def test_run_agent_corrupt_explanation(self):+ from run_agent import AIAgent++ explanation = AIAgent._format_turn_completion_explanation(+ "session_persistence_failed", "corrupt"+ )+ assert LIVE_DB_SALVAGE_COMMAND not in explanation+ assert "hermes sessions recover --source" in explanation+ assert ".recover" in explanation # the warning still names the hazard++ def test_repair_budget_error_names_safe_lane(self, tmp_path: Path):+ import hermes_state++ message = hermes_state._persistent_repair_exhausted_error(+ tmp_path / "state.db"+ )+ assert "Manual recovery required" in message+ assert "sessions recover --source" in message+ # The old shape embedded the live path straight into a raw sqlite3+ # command: `sqlite3 {db_path} ".recover"`.+ assert ".recover\"`" not in message+ assert "do NOT" in message++ def test_forensic_backup_refusals_name_safe_lane(self):+ """The low-disk and stat-failure forensic backup refusal strings+ must not embed a raw sqlite3 command against the live path."""+ import hermes_state++ body = inspect.getsource(hermes_state._backup_db_file)+ assert ".recover\"`" not in body+ assert "sessions recover --source" in body++ def test_kanban_manual_recovery_warns_about_live_db(self):+ import hermes_cli.kanban as kanban++ source = inspect.getsource(kanban)+ assert '`sqlite3 kanban.db ".recover"`' not in source+ assert "copy kanban.db aside FIRST" in sourcediff --git a/tests/run_agent/test_corruption_recovery_guidance.py b/tests/run_agent/test_corruption_recovery_guidance.pyindex e4b5063ff7b..155d326e206 100644--- a/tests/run_agent/test_corruption_recovery_guidance.py+++ b/tests/run_agent/test_corruption_recovery_guidance.py@@ -31,6 +31,27 @@ def test_format_turn_completion_corrupt_includes_recovery_options():assert "Freeing disk space will not help" in explanation+def test_format_turn_completion_corrupt_never_names_the_live_db():+ """The 'corrupt' cause must not direct a raw sqlite3 shell at the live DB.++ #100368 forensics: the system sqlite3 CLI on Debian/Ubuntu (3.45.1/+ 3.46.1, below the 3.51.x WAL-reset fix) unlinks the live WAL/SHM pair+ when pointed at a live state.db, splitting the store into two+ generations whose acknowledged writes vanish. The guidance that ships+ in the corruption banner must be the snapshot-copying+ `hermes sessions recover` lane.+ """+ from run_agent import AIAgent++ explanation = AIAgent._format_turn_completion_explanation(+ "session_persistence_failed", "corrupt"+ )+ assert "sessions recover" in explanation+ assert 'sqlite3 ~/.hermes/state.db ".recover"' not in explanation+ # The replacement guidance names the safe command.+ assert "hermes sessions recover --source" in explanation++def test_format_turn_completion_disk_still_advises_space():"""The 'disk' cause still gives disk-space advice (unchanged)."""from run_agent import AIAgentdiff --git a/tests/test_state_db_repair_loop_cap.py b/tests/test_state_db_repair_loop_cap.pyindex 7293d7a641f..0eafbcb7a3d 100644--- a/tests/test_state_db_repair_loop_cap.py+++ b/tests/test_state_db_repair_loop_cap.py@@ -82,6 +82,13 @@ class TestPersistentAttemptCap:assert report["repaired"] is Falseassert "Manual recovery required" in report["error"]assert ".recover" in report["error"]+ assert "sessions recover" in report["error"]+ assert "sqlite3" in report["error"]+ # The terminal error must not direct a raw sqlite3 shell at the+ # live database: a WAL-reset-vulnerable CLI (Debian/Ubuntu 3.45.x/+ # 3.46.x, pre-#100368 forensics) unlinks the live WAL/SHM pair+ # and splits the store into two generations.+ assert 'sqlite3 state.db ".recover"' not in report["error"]assert len(_existing_malformed_backups(db)) == backups_beforedef test_changed_file_resets_the_budget(self, tmp_path):