The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): salvage a page-1-header-damaged state.db in the lost_and_found lane
TaoMasterCoder10777823fe80
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..5c1f36eb5b5--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+TaoMasterCoder+# PR #102808 salvage (header-damaged state.db in lost_and_found lane; #106667)diff --git a/hermes_cli/session_lost_and_found.py b/hermes_cli/session_lost_and_found.pyindex ee2f36cd664..d915532c24f 100644--- a/hermes_cli/session_lost_and_found.py+++ b/hermes_cli/session_lost_and_found.py@@ -180,10 +180,41 @@ def _cli_supports_recover(binary: str) -> bool:shutil.rmtree(scratch_dir, ignore_errors=True)+SQLITE_HEADER_LENGTH = 100++def run_cli_lost_and_found_recover(source: Path, lf_path: Path, sqlite3_bin: str, *, timeout: float = 3600.0,) -> dict[str, Any]:- """Run ``sqlite3 <source> .recover`` streamed into a fresh scratch DB."""+ """Run ``sqlite3 <source> .recover`` streamed into a fresh scratch DB.++ A file whose page-1 header is garbage (SIGKILL mid-write) is refused outright by the shell+ (``file is not a database``, rc 26) although the data pages after it survive. ``.recover``+ walks pages via sqlite_dbpage and only trips on the magic check, so on that refusal the+ 100-byte header of the private snapshot is zeroed and the attempts rerun; a zeroed header+ makes .recover infer page size and layout from the pages themselves (a spliced donor header+ would instead report a database size/freelist that contradicts the file). ``source`` is+ the caller's snapshot copy, never the user's file (#106667).+ """+ attempts = _cli_recover_attempts(source, lf_path, sqlite3_bin, timeout=timeout)+ if attempts[-1]["usable"]:+ return {"binary": sqlite3_bin, "attempts": attempts}+ if any("not a database" in a["dump_stderr_tail"] for a in attempts):+ with source.open("r+b") as handle:+ handle.write(bytes(SQLITE_HEADER_LENGTH))+ attempts += _cli_recover_attempts(source, lf_path, sqlite3_bin, timeout=timeout)+ if attempts[-1]["usable"]:+ return {"binary": sqlite3_bin, "attempts": attempts, "header_zeroed": True}+ details = "; ".join(+ f"[{a['command']}] dump rc={a['dump_returncode']} load rc={a['load_returncode']} "+ f"{a['dump_stderr_tail'] or a['load_stderr_tail']}".strip()+ for a in attempts+ )+ raise LostAndFoundError(f"sqlite3 .recover did not produce a usable lost_and_found database: {details}")+++def _cli_recover_attempts(source: Path, lf_path: Path, sqlite3_bin: str, *, timeout: float) -> list[dict[str, Any]]:+ """``--ignore-freelist`` first (no resurrected deleted rows), plain ``.recover`` for older shells."""attempts: list[dict[str, Any]] = []for command in (".recover --ignore-freelist", ".recover"):if lf_path.exists():@@ -211,13 +242,8 @@ def run_cli_lost_and_found_recover("usable": _lost_and_found_db_usable(lf_path),})if attempts[-1]["usable"]:- return {"binary": sqlite3_bin, "attempts": attempts}- details = "; ".join(- f"[{a['command']}] dump rc={a['dump_returncode']} load rc={a['load_returncode']} "- f"{a['dump_stderr_tail'] or a['load_stderr_tail']}".strip()- for a in attempts- )- raise LostAndFoundError(f"sqlite3 .recover did not produce a usable lost_and_found database: {details}")+ break+ return attemptsdef _lost_and_found_db_usable(lf_path: Path) -> bool:diff --git a/hermes_cli/session_recovery.py b/hermes_cli/session_recovery.pyindex 9659beb9fd5..6dae8774327 100644--- a/hermes_cli/session_recovery.py+++ b/hermes_cli/session_recovery.py@@ -1040,6 +1040,12 @@ def _recover_via_lost_and_found("BEST-EFFORT page-level salvage: the source table schemas were unreadable, so rows were rebuilt from raw ""pages and mapped heuristically. Review every count before trusting this output.")+ if cli_report.get("header_zeroed"):+ verification["warnings"].append(+ "header salvage: SQLite refused the source outright (page-1 header damaged, 'file is not a "+ "database'); the header of the private snapshot copy was zeroed so .recover could walk the "+ "surviving pages. Rows written only to a -wal after the last checkpoint are not included."+ )verification.update(loss_detected=True, complete=False)# Structural checks cannot see a positional mis-mapping: every row still inserts, so integrity/FK/FTS# stay green. A systematic timestamp violation is the semantic tell — never report such a salvage as verified.diff --git a/tests/hermes_cli/test_session_recovery_lost_and_found.py b/tests/hermes_cli/test_session_recovery_lost_and_found.pyindex a8711dde867..0046804c1d8 100644--- a/tests/hermes_cli/test_session_recovery_lost_and_found.py+++ b/tests/hermes_cli/test_session_recovery_lost_and_found.py@@ -305,6 +305,54 @@ def test_lost_and_found_lane_recovers_schema_unreadable_source(recovered_db.close()++ not HAVE_SQLITE3_CLI,+ reason="sqlite3 CLI not on PATH; .recover is a shell-only feature",+)+def test_lost_and_found_lane_recovers_page1_header_damaged_source(tmp_path: Path) -> None:+ """#106667: a garbage page-1 header makes SQLite (and the shell's .recover) refuse the file+ with 'file is not a database' although every data page survives. The lane must still+ salvage the rows, and must do it on its snapshot — the user's file stays byte-identical."""+ source = tmp_path / "header-damaged.db"+ output = tmp_path / "header-recovered.db"+ db = SessionDB(db_path=source)+ try:+ for session_number in range(3):+ session_id = f"hdr-session-{session_number}"+ db.create_session(session_id, "cli", cwd="/tmp/hdr")+ for message_number in range(9):+ db.append_message(session_id, "user", f"payload {session_number} {message_number}")+ finally:+ db.close()+ conn = sqlite3.connect(str(source), isolation_level=None)+ try:+ conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ conn.execute("PRAGMA journal_mode=DELETE")+ finally:+ conn.close()+ data = bytearray(source.read_bytes())+ data[0:100] = bytes(range(1, 101)) # not the magic, not zeroes: the incident shape+ source.write_bytes(data)+ damaged_bytes = source.read_bytes()++ with pytest.raises(sqlite3.DatabaseError, match="not a database"):+ sqlite3.connect(str(source)).execute("SELECT count(*) FROM sqlite_master").fetchone()++ report = recover_session_database(source, output, work_dir=tmp_path, allow_partial=True)++ assert report["mode"] == "lost_and_found_salvage"+ assert report["sqlite3_cli"]["header_zeroed"] is True+ assert any("header salvage" in warning for warning in report["verification"]["warnings"])+ assert source.read_bytes() == damaged_bytes+ conn = sqlite3.connect(str(output))+ try:+ assert conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0] == 3+ assert conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 27+ finally:+ conn.close()++# ── mapper unit tests (no sqlite3 CLI required) ─────────────────────────────