The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): detect Windows database holders before maintenance
JoaoMarcos446c71ff2bd769
diff --git a/.github/workflows/windows-venv-e2e.yml b/.github/workflows/windows-venv-e2e.ymlindex 7c874e74b9f..f785d881331 100644--- a/.github/workflows/windows-venv-e2e.yml+++ b/.github/workflows/windows-venv-e2e.yml@@ -58,6 +58,7 @@ jobs:set -uo pipefailuv run --no-sync python -m pytest \tests/hermes_cli/test_venv_holder_windows_live.py \+ tests/hermes_state/test_state_db_holders_windows_live.py \tests/hermes_cli/test_taskkill_identity_windows_live.py \tests/hermes_cli/test_git_trampoline_windows_live.py \tests/hermes_cli/test_managed_uv_windows_cutover.py \diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex d3b76f77107..228adb7725c 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -94,9 +94,6 @@ def _report_database_holders(name: str, db_path: Path) -> None:offline journal-mode conversion; a partial or unavailable scan is reported as "cannot prove quiet", never asan all-clear (the scan is the same fail-closed authority repair/VACUUM/checkpoint admission uses)."""from hermes_state_holders import describe_holder_pid, foreign_state_db_holders- if sys.platform == "win32":- check_warn(f"{name}: cannot prove the database is quiet", "(holder scan is unavailable on Windows)")- returnunknown: list[str] = []by_pid: dict[int, set[str]] = {}for pid, target in foreign_state_db_holders(db_path):diff --git a/hermes_cli/sessions_cmd_journal_mode.py b/hermes_cli/sessions_cmd_journal_mode.pyindex 9eabdf6bb96..18db510b664 100644--- a/hermes_cli/sessions_cmd_journal_mode.py+++ b/hermes_cli/sessions_cmd_journal_mode.py@@ -10,7 +10,6 @@ ANY foreign process holds the file or a sidecar (``foreign_state_db_holders``),from __future__ import annotationsimport sqlite3-import sysfrom pathlib import Pathfrom typing import Optional@@ -28,8 +27,8 @@ def _header_mode(db_path: Path) -> str:return _MODE_BY_HEADER_VERSION.get((head[18], head[19]), f"unknown({head[18]}/{head[19]})")-def _refusal(target: str, current: str, platform: str, *, on_cross_vm_fs: bool, force: bool) -> Optional[str]:- """Admission checks that need no I/O, with the platform passed as data so tests need not fake the host."""+def _refusal(target: str, current: str, *, on_cross_vm_fs: bool) -> Optional[str]:+ """Admission checks independent of holder discovery, which is enforced for every platform."""if current == "not-a-database" or current.startswith("unknown("):return (f"its file header reads {current}, so it is not a Hermes SQLite store this command can convert ""(pass --db PATH to point at one).")@@ -37,11 +36,6 @@ def _refusal(target: str, current: str, platform: str, *, on_cross_vm_fs: bool,return ("WAL shared memory silently corrupts on cross-VM filesystems (virtiofs/9p — Docker Desktop, ""OrbStack, Lima bind mounts). Keep this store on journal_mode=delete or move it to a native ""filesystem.")- if platform == "win32" and not force:- # foreign_state_db_holders() has no Windows scan and returns [] there: an empty holder list is- # "unknown", never "nobody holds it", so the gate must refuse rather than issue a silent all-clear.- return ("cannot prove the database is quiet on Windows — no holder scan. Stop the gateway, dashboard, "- "cron and every CLI, then re-run with --force.")return None@@ -65,9 +59,7 @@ def cmd_set_journal_mode(args) -> int:print(f"✓ {db_path} is already journal_mode={target}.")return 0refusal = _refusal(- target, current, sys.platform,- on_cross_vm_fs=target == "wal" and _path_on_cross_vm_fs(str(db_path)),- force=bool(getattr(args, "force", False)),+ target, current, on_cross_vm_fs=target == "wal" and _path_on_cross_vm_fs(str(db_path)))if refusal:print(f"✗ Refusing to change the journal mode of {db_path}: {refusal}")diff --git a/hermes_cli/subcommands/sessions.py b/hermes_cli/subcommands/sessions.pyindex 33306507f31..5cd9698fc39 100644--- a/hermes_cli/subcommands/sessions.py+++ b/hermes_cli/subcommands/sessions.py@@ -185,8 +185,7 @@ def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:sessions_set_journal_mode.add_argument("--db", default=None, metavar="PATH",help="Convert another Hermes SQLite store (e.g. kanban.db) instead of the profile's state.db")_flag(sessions_set_journal_mode, "--force",- help="Windows only: proceed without the holder scan (which does not exist there) after stopping "- "every Hermes process yourself")+ help="Deprecated compatibility flag; holder verification is mandatory on every platform")sessions_repair_routing = sessions_subparsers.add_parser("repair-routing", help="Re-stamp gateway sessions that lost their routing identity",diff --git a/hermes_state_holders.py b/hermes_state_holders.pyindex 9143a9b3cd8..3f1bda1f1b4 100644--- a/hermes_state_holders.py+++ b/hermes_state_holders.py@@ -321,6 +321,92 @@ def _argv_scoped_to_other_home(argv: Sequence[str], db_path: Path) -> bool:return other_home_seen+def _windows_restart_manager_holders(db_path: Path) -> List[Tuple[int, str]]:+ """Return foreign processes using state.db or a WAL sidecar via Windows Restart Manager."""+ import ctypes+ from ctypes import wintypes++ error_more_data = 234+ max_app_name, max_svc_name = 255, 63++ class _UniqueProcess(ctypes.Structure):+ _fields_ = [("pid", wintypes.DWORD), ("started", wintypes.FILETIME)]++ class _ProcessInfo(ctypes.Structure):+ _fields_ = [+ ("process", _UniqueProcess),+ ("app_name", wintypes.WCHAR * (max_app_name + 1)),+ ("service_name", wintypes.WCHAR * (max_svc_name + 1)),+ ("app_type", wintypes.DWORD),+ ("app_status", wintypes.ULONG),+ ("ts_session_id", wintypes.DWORD),+ ("restartable", wintypes.BOOL),+ ]++ api = ctypes.WinDLL("rstrtmgr", use_last_error=True)+ start, register, get_list, end = (+ api.RmStartSession, api.RmRegisterResources, api.RmGetList, api.RmEndSession+ )+ start.argtypes = [ctypes.POINTER(wintypes.DWORD), wintypes.DWORD, wintypes.LPWSTR]+ register.argtypes = [+ wintypes.DWORD, wintypes.UINT, ctypes.POINTER(wintypes.LPCWSTR),+ wintypes.UINT, ctypes.c_void_p, wintypes.UINT, ctypes.c_void_p,+ ]+ get_list.argtypes = [+ wintypes.DWORD, ctypes.POINTER(wintypes.UINT), ctypes.POINTER(wintypes.UINT),+ ctypes.POINTER(_ProcessInfo), ctypes.POINTER(wintypes.DWORD),+ ]+ end.argtypes = [wintypes.DWORD]+ for fn in (start, register, get_list, end):+ fn.restype = wintypes.DWORD++ resources = [+ os.path.abspath(path)+ for path in (os.fspath(db_path), os.fspath(db_path) + "-wal", os.fspath(db_path) + "-shm")+ if os.path.exists(path)+ ]+ if not resources:+ return []++ session = wintypes.DWORD()+ key = ctypes.create_unicode_buffer(33)+ rc = start(ctypes.byref(session), 0, key)+ if rc:+ raise OSError(rc, "RmStartSession failed")+ try:+ filenames = (wintypes.LPCWSTR * len(resources))(*resources)+ rc = register(session, len(resources), filenames, 0, None, 0, None)+ if rc:+ raise OSError(rc, "RmRegisterResources failed")++ needed, count, reasons = wintypes.UINT(), wintypes.UINT(), wintypes.DWORD()+ rc = get_list(session, ctypes.byref(needed), ctypes.byref(count), None, ctypes.byref(reasons))+ if rc == 0:+ return []+ if rc != error_more_data:+ raise OSError(rc, "RmGetList failed")++ # The process set can change between the sizing and data calls. Retry the bounded race.+ for _ in range(3):+ apps = (_ProcessInfo * needed.value)()+ count = wintypes.UINT(needed.value)+ rc = get_list(+ session, ctypes.byref(needed), ctypes.byref(count), apps, ctypes.byref(reasons)+ )+ if rc == 0:+ own_pid = os.getpid()+ return [+ (int(apps[index].process.pid), os.path.abspath(os.fspath(db_path)))+ for index in range(count.value)+ if int(apps[index].process.pid) != own_pid+ ]+ if rc != error_more_data:+ raise OSError(rc, "RmGetList failed")+ raise RuntimeError("Restart Manager holder set kept changing")+ finally:+ end(session)++def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:"""Return foreign holders of the DB or one of its WAL sidecars.@@ -329,7 +415,14 @@ def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:still be open by another process."""if _IS_WINDOWS:- return []+ try:+ return _windows_restart_manager_holders(db_path)+ except Exception as exc:+ logger.warning(+ "Could not prove state.db has no Windows holders; deferring structural maintenance: %s",+ exc,+ )+ return [(-1, f"Windows Restart Manager scan failed: {exc}")]# realpath, not abspath: psutil/libproc report the kernel-resolved pathname, so a symlinked# HERMES_HOME would otherwise make every holder invisible and let maintenance proceed.diff --git a/tests/hermes_cli/test_doctor_journal_modes.py b/tests/hermes_cli/test_doctor_journal_modes.pyindex fc0ddf5d466..a2fef61bd67 100644--- a/tests/hermes_cli/test_doctor_journal_modes.py+++ b/tests/hermes_cli/test_doctor_journal_modes.py@@ -426,7 +426,6 @@ class TestConfiguredDeleteNeverApplied:assert "state.db: WAL journal mode" not in outassert ("To clear the exposure:" in out) is exposed- @pytest.mark.skipif(sys.platform == "win32", reason="holder scan has no Windows backend")def test_wal_db_under_configured_delete_names_its_holders(self, tmp_path, capsys, monkeypatch):# The offline conversion needs the file quiet, so doctor must say WHICH process to stop — a# subprocess holding a real connection is named by PID; the doctor process itself is not a holder.diff --git a/tests/hermes_cli/test_sessions_set_journal_mode.py b/tests/hermes_cli/test_sessions_set_journal_mode.pyindex 44588a13b21..2e23264d9e5 100644--- a/tests/hermes_cli/test_sessions_set_journal_mode.py+++ b/tests/hermes_cli/test_sessions_set_journal_mode.py@@ -26,8 +26,6 @@ def _wal_store(path):def _args(mode, db=None, force=True):- # --force only waives the Windows "no holder scan" refusal; on POSIX the scan still gates the flip,- # so passing it keeps the happy path exercised on every lane including windows-latest.return argparse.Namespace(sessions_action="set-journal-mode", mode=mode, db=db, force=force)@@ -47,8 +45,6 @@ def test_set_journal_mode_converts_wal_store_offline(tmp_path, monkeypatch, capsassert "wal → delete" in capsys.readouterr().out[email protected](sys.platform == "win32",- reason="foreign_state_db_holders has no Windows scan; the --force refusal covers that lane")def test_set_journal_mode_refuses_while_another_process_holds_the_store(tmp_path, monkeypatch, capsys):db = tmp_path / "state.db"_wal_store(db)@@ -72,22 +68,17 @@ def test_set_journal_mode_refuses_while_another_process_holds_the_store(tmp_pathassert db.read_bytes()[18:20] == b"\x02\x02", "a refused switch must leave the file untouched"[email protected]("target,current,platform,cross_vm,force,expected", [- # Windows has no holder scan (foreign_state_db_holders returns []): an empty list must never read- # as "nobody holds it", so the gate refuses instead of issuing a silent all-clear.- ("delete", "wal", "win32", False, False, "no holder scan"),- ("delete", "wal", "win32", False, True, None),- ("delete", "wal", "linux", False, False, None),- # WAL shared memory corrupts on virtiofs/9p, so ENABLING it there is refused, --force or not.- ("wal", "delete", "linux", True, False, "cross-VM filesystems"),- ("wal", "delete", "win32", True, True, "cross-VM filesystems"),- ("delete", "wal", "linux", True, False, None),[email protected]("target,current,cross_vm,expected", [+ ("delete", "wal", False, None),+ # WAL shared memory corrupts on virtiofs/9p, so ENABLING it there is refused.+ ("wal", "delete", True, "cross-VM filesystems"),+ ("delete", "wal", True, None),# A garbage or unrecognised header is reported, never handed to sqlite3 for a raw traceback.- ("delete", "not-a-database", "linux", False, False, "not a Hermes SQLite store"),- ("delete", "unknown(3/3)", "linux", False, True, "not a Hermes SQLite store"),+ ("delete", "not-a-database", False, "not a Hermes SQLite store"),+ ("delete", "unknown(3/3)", False, "not a Hermes SQLite store"),])-def test_refusal_admission_invariants(target, current, platform, cross_vm, force, expected):- reason = _refusal(target, current, platform, on_cross_vm_fs=cross_vm, force=force)+def test_refusal_admission_invariants(target, current, cross_vm, expected):+ reason = _refusal(target, current, on_cross_vm_fs=cross_vm)if expected is None:assert reason is Noneelse:diff --git a/tests/hermes_state/test_state_db_holders.py b/tests/hermes_state/test_state_db_holders.pyindex 4fb5c24f383..1d02dfc8c88 100644--- a/tests/hermes_state/test_state_db_holders.py+++ b/tests/hermes_state/test_state_db_holders.py@@ -48,3 +48,38 @@ def test_foreign_holder_accepts_same_inode_reached_through_an_alias(assert hermes_state_holders.foreign_state_db_holders(db_path) == [(222, str(alias_path))]++++def test_windows_holder_scan_delegates_to_restart_manager(monkeypatch, tmp_path):+ db_path = tmp_path / "state.db"+ db_path.touch()+ seen = []++ monkeypatch.setattr(hermes_state_holders, "_IS_WINDOWS", True)+ monkeypatch.setattr(+ hermes_state_holders,+ "_windows_restart_manager_holders",+ lambda path: seen.append(path) or [(4242, str(path))],+ )++ assert hermes_state_holders.foreign_state_db_holders(db_path) == [(4242, str(db_path))]+ assert seen == [db_path]+++def test_windows_holder_scan_failure_fails_closed(monkeypatch, tmp_path):+ db_path = tmp_path / "state.db"+ db_path.touch()++ monkeypatch.setattr(hermes_state_holders, "_IS_WINDOWS", True)++ def fail(_path):+ raise OSError("Restart Manager unavailable")++ monkeypatch.setattr(hermes_state_holders, "_windows_restart_manager_holders", fail)++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert holders[0][0] == -1+ assert "Restart Manager scan failed" in holders[0][1]+ refusal = hermes_state_holders.held_store_refusal(db_path, command="optimize-storage")+ assert refusal is not None and "cannot prove the database is quiet" in refusaldiff --git a/tests/hermes_state/test_state_db_holders_windows_live.py b/tests/hermes_state/test_state_db_holders_windows_live.pynew file mode 100644index 00000000000..dcaebc16f54--- /dev/null+++ b/tests/hermes_state/test_state_db_holders_windows_live.py@@ -0,0 +1,48 @@+"""Live Windows proof for #120205: structural maintenance sees a real foreign SQLite holder."""++import sqlite3+import subprocess+import sys++import pytest++from hermes_state_holders import foreign_state_db_holders, held_store_refusal++pytestmark = pytest.mark.windows_only+++def test_restart_manager_finds_real_foreign_state_db_holder(tmp_path):+ db = tmp_path / "state.db"+ conn = sqlite3.connect(db)+ conn.execute("CREATE TABLE t(x)")+ conn.commit()+ conn.close()++ holder = subprocess.Popen(+ [+ sys.executable,+ "-c",+ (+ "import sqlite3,sys; "+ "c=sqlite3.connect(sys.argv[1]); "+ "c.execute('SELECT count(*) FROM t').fetchone(); "+ "print('held', flush=True); sys.stdin.readline()"+ ),+ str(db),+ ],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ text=True,+ )+ try:+ assert holder.stdout.readline().strip() == "held"+ holders = foreign_state_db_holders(db)+ assert any(pid == holder.pid for pid, _ in holders), holders+ refusal = held_store_refusal(db, command="optimize-storage")+ assert refusal is not None and f"PID {holder.pid}" in refusal+ finally:+ holder.stdin.write("\n")+ holder.stdin.flush()+ holder.wait(timeout=30)++ assert foreign_state_db_holders(db) == []