The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): scope uninspectable-holder fallback to the instance's own HERMES_HOME
TaoMasterCoder085623a11a0c
diff --git a/hermes_state_holders.py b/hermes_state_holders.pyindex 9f4176d40a8..7727cdbe678 100644--- a/hermes_state_holders.py+++ b/hermes_state_holders.py@@ -125,6 +125,59 @@ def canonical_sqlite_path(path: str) -> str:return os.path.normcase(os.path.abspath(path.removesuffix(" (deleted)")))+def _argv_scoped_to_other_home(argv: Sequence[str], db_path: Path) -> bool:+ """Return whether argv proves the process belongs to a DIFFERENT instance.++ ``state.db`` lives at the HERMES_HOME root, so an absolute-path token+ containing a ``/.hermes`` segment (or naming a ``state.db``/WAL/SHM under+ some other parent) identifies that token's own Hermes home. When at least+ one such token exists AND no token references this instance's state.db,+ its sidecars, or its home directory, the process provably works on a+ different generation and must not be counted as an uninspectable holder+ of ours (issue #92401: a second gateway under /home/demo/.hermes deferred+ this instance's stale-FTS rebuild forever despite lsof proving zero open+ handles). Ambiguous argv without absolute-path tokens returns False and+ keeps the fail-closed suspicion.+ """+ db_path_str = os.path.abspath(os.fspath(db_path))+ this_home = os.path.dirname(db_path_str)+ ours = {+ os.path.normcase(candidate)+ for candidate in (+ db_path_str,+ db_path_str + "-wal",+ db_path_str + "-shm",+ this_home,+ )+ }+ other_home_seen = False+ for token in argv:+ if not isinstance(token, str):+ continue+ if token.startswith("/"):+ path_token = token+ elif token.startswith("-") and "=" in token:+ # ``--db=/abs/path``-style options carry a path value; anchor on+ # the text after '=' so normpath does not prepend the option.+ value = token.split("=", 1)[1]+ path_token = value if value.startswith("/") else None+ else:+ path_token = None+ if path_token is not None:+ normalized = os.path.normcase(os.path.normpath(path_token))+ if normalized in ours or normalized.startswith(this_home + os.sep):+ return False+ if "/.hermes" in normalized or normalized.endswith("/.hermes"):+ other_home_seen = True+ elif os.path.basename(normalized) in (+ "state.db",+ "state.db-wal",+ "state.db-shm",+ ):+ other_home_seen = True+ return other_home_seen++def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:"""Return foreign holders of the DB or one of its WAL sidecars.@@ -171,7 +224,11 @@ def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:fds = os.listdir(fd_dir)except OSError:argv = _read_proc_argv(pid)- if argv is not None and _looks_like_hermes(argv):+ if (+ argv is not None+ and _looks_like_hermes(argv)+ and not _argv_scoped_to_other_home(argv, db_path)+ ):cmdline = " ".join(argv)holders.append((pid, f"uninspectable holder: {cmdline[:80]}"))continue@@ -183,7 +240,11 @@ def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:if exc.errno in (errno.ENOENT, errno.ESRCH):continueargv = _read_proc_argv(pid)- if argv is not None and _looks_like_hermes(argv):+ if (+ argv is not None+ and _looks_like_hermes(argv)+ and not _argv_scoped_to_other_home(argv, db_path)+ ):holders.append((pid,@@ -203,7 +264,11 @@ def foreign_state_db_holders(db_path: Path) -> List[Tuple[int, str]]:)else:argv = _read_proc_argv(pid)- if argv is not None and _looks_like_hermes(argv):+ if (+ argv is not None+ and _looks_like_hermes(argv)+ and not _argv_scoped_to_other_home(argv, db_path)+ ):holders.append((pid,diff --git a/tests/state/test_fts_holder_instance_scope.py b/tests/state/test_fts_holder_instance_scope.pynew file mode 100644index 00000000000..969cae6a2fb--- /dev/null+++ b/tests/state/test_fts_holder_instance_scope.py@@ -0,0 +1,270 @@+"""Instance-scoping of the uninspectable-holder fallback.++Field-verified 2026-09-07 on a production host running TWO independent+Hermes instances: a main gateway (user ``ubuntu``,+HERMES_HOME=/home/ubuntu/.hermes) and a demo gateway (user ``demo``,+HERMES_HOME=/home/demo/.hermes). The demo gateway runs as another user, so+its ``/proc/<pid>/fd`` table is unreadable from the main instance and the+holder scan falls back to ``/proc/<pid>/cmdline`` + ``_looks_like_hermes``.+The demo process's argv matches the Hermes patterns exactly, so the fallback+flagged it as an uninspectable holder of the MAIN instance's state.db even+though ``lsof`` proved zero open handles on it. Consequence: the stale-FTS+rebuild in ``hermes_state_schema._recover_stale_fts`` was deferred 42 times+across 6 gateway restarts, the ``fts_stale`` breadcrumb never cleared, and+FTS self-repair stayed permanently disabled.++PR #92419 fixed substring false positives (journalctl/grep mentioning+hermes); a genuine second instance with a DIFFERENT HERMES_HOME is still+misjudged on current main (issue #92401).++Behavior contract: an uninspectable holder identified only by argv must be+counted unless its own argv proves it is scoped to a *different* Hermes+home / state.db and never references ours. Ambiguous argv (no absolute+paths at all) must remain fail-closed, exactly as before — the conservative+intent of the fallback is preserved.+"""++import os++import pytest++import hermes_state_holders++# Capture the pristine stdlib functions at import time: monkeypatched calls+# re-enter these closures, and re-capturing ``os.listdir`` after a previous+# patch would compose the fakes into a double path-rewrite.+_REAL_LISTDIR = os.listdir+_REAL_READLINK = os.readlink+++# Representative demo-gateway argv on the two-instance host: every absolute+# token lives under /home/demo/.hermes, the binary name matches the Hermes+# patterns, and nothing references the main instance's home or state.db.+DEMO_HOME_ARGV = [+ "/home/demo/.hermes/hermes-agent/hermes",+ "gateway",+ "run",+]++# Same, spelled through the venv interpreter + hermes launcher script.+DEMO_VENV_ARGV = [+ "/home/demo/.hermes/hermes-agent/venv/bin/python",+ "/home/demo/.hermes/hermes-agent/hermes_cli/main.py",+ "gateway",+]++# A Hermes-shaped argv with no absolute paths: cannot disprove that this+# process touches our state.db, so it must stay fail-closed.+AMBIGUOUS_ARGV = ["hermes", "gateway", "run"]+++def _install_fake_proc(monkeypatch, tmp_path, unreadable_pids=(), fd_pids=()):+ """Redirect the module's /proc access to an inert fake tree.++ PIDs in ``unreadable_pids`` raise PermissionError on their fd dir+ (cross-user process); PIDs in ``fd_pids`` expose an empty-but-listable+ fd dir whose single descriptor fails readlink with EACCES+ (uninspectable-descriptor branch).+ """+ proc_root = tmp_path / "proc"+ for pid in set(unreadable_pids) | set(fd_pids):+ (proc_root / str(pid)).mkdir(parents=True, exist_ok=True)+ for pid in fd_pids:+ (proc_root / str(pid) / "fd").mkdir(exist_ok=True)+ (proc_root / str(pid) / "fd" / "3").touch(exist_ok=True)++ monkeypatch.setattr(hermes_state_holders.os, "getpid", lambda: 111)++ def _listdir(path):+ if isinstance(path, str):+ for pid in unreadable_pids:+ if path == f"/proc/{pid}/fd":+ raise PermissionError(errno_value("EACCES"), path)+ path = path.replace("/proc", str(proc_root))+ return _REAL_LISTDIR(path)++ monkeypatch.setattr(hermes_state_holders.os, "listdir", _listdir)++ def _readlink(path):+ if "222/fd/3" in str(path):+ raise PermissionError(errno_value("EACCES"), str(path))+ return _REAL_READLINK(str(path).replace("/proc", str(proc_root)))++ monkeypatch.setattr(hermes_state_holders.os, "readlink", _readlink)+++def errno_value(name):+ import errno++ return getattr(errno, name)+++def _install_fake_argv(monkeypatch, argv_by_pid):+ monkeypatch.setattr(+ hermes_state_holders,+ "_read_proc_argv",+ lambda pid: list(argv_by_pid.get(pid)) if pid in argv_by_pid else None,+ )++[email protected]_only+class TestUninspectableHolderInstanceScope:+ def test_other_instance_argv_is_not_a_holder_of_our_db(self, tmp_path, monkeypatch):+ """RED: fd dir unreadable + argv proves the process belongs to a+ DIFFERENT Hermes home → not a holder of our state.db."""+ db_path = tmp_path / "state.db"+ _install_fake_proc(monkeypatch, tmp_path, unreadable_pids=(222,))+ _install_fake_argv(monkeypatch, {222: DEMO_HOME_ARGV})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert holders == []++ def test_other_instance_venv_argv_is_not_a_holder(self, tmp_path, monkeypatch):+ db_path = tmp_path / "state.db"+ _install_fake_proc(monkeypatch, tmp_path, unreadable_pids=(222,))+ _install_fake_argv(monkeypatch, {222: DEMO_VENV_ARGV})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert holders == []++ def test_uninspectable_descriptor_other_instance_is_not_a_holder(+ self, tmp_path, monkeypatch+ ):+ """Sibling branch: fd listable but readlink EACCES — same scoping."""+ db_path = tmp_path / "state.db"+ _install_fake_proc(monkeypatch, tmp_path, fd_pids=(222,))+ _install_fake_argv(monkeypatch, {222: DEMO_HOME_ARGV})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert holders == []++ def test_argv_referencing_our_db_stays_flagged(self, tmp_path, monkeypatch):+ """A (possibly second) instance whose argv names OUR state.db, our+ sidecars, or our home must still be fail-closed flagged."""+ db_path = tmp_path / "state.db"+ our_home = str(tmp_path)++ for argv in (+ ["hermes", f"--db={db_path}", "gateway"],+ ["hermes", "checkpoint", f"{db_path}-wal"],+ ["hermes", "--home", our_home, "gateway"],+ ):+ assert hermes_state_holders._looks_like_hermes(argv) or argv[0] == "hermes"+ _install_fake_proc(monkeypatch, tmp_path, unreadable_pids=(222,))+ _install_fake_argv(monkeypatch, {222: argv})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert [pid for pid, _ in holders] == [222], argv+ assert holders[0][1].startswith("uninspectable holder:"), argv++ def test_ambiguous_argv_without_absolute_paths_stays_flagged(+ self, tmp_path, monkeypatch+ ):+ """Conservative behavior unchanged: argv with no absolute paths can+ not disprove the suspicion, so the holder is still reported."""+ db_path = tmp_path / "state.db"+ _install_fake_proc(monkeypatch, tmp_path, unreadable_pids=(222,))+ _install_fake_argv(monkeypatch, {222: AMBIGUOUS_ARGV})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert [pid for pid, _ in holders] == [222]+ assert holders[0][1].startswith("uninspectable holder:")++ def test_uninspectable_descriptor_ambiguous_argv_stays_flagged(+ self, tmp_path, monkeypatch+ ):+ db_path = tmp_path / "state.db"+ _install_fake_proc(monkeypatch, tmp_path, fd_pids=(222,))+ _install_fake_argv(monkeypatch, {222: AMBIGUOUS_ARGV})++ holders = hermes_state_holders.foreign_state_db_holders(db_path)+ assert [pid for pid, _ in holders] == [222]+ assert holders[0][1].startswith("uninspectable descriptor:")+++class TestArgvScopedToOtherHome:+ """Unit contract for the pure scoping helper."""++ def test_helper_exists_and_is_pure(self, tmp_path):+ db_path = tmp_path / "state.db"+ helper = hermes_state_holders._argv_scoped_to_other_home+ # No /proc access needed: pure function of (argv, db_path).+ assert helper([], db_path) is False+ assert helper(["hermes", "gateway"], db_path) is False++ def test_relative_tokens_are_ignored(self, tmp_path):+ """A relative-looking 'hermes' token cannot prove instance scope."""+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ ["hermes", ".hermes/relative/config.yaml", "gateway"], db_path+ )+ is False+ )++ def test_token_equal_to_our_db_wal_keeps_flag(self, tmp_path):+ """A sidecar of OUR db referenced by an other-home binary is still+ our problem — any reference to ours vetoes the exemption."""+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ ["/home/demo/.hermes/hermes-agent/hermes", f"{db_path}-wal"], db_path+ )+ is False+ )++ def test_other_home_and_our_home_tokens_together_keep_flag(self, tmp_path):+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ [+ "/home/demo/.hermes/hermes-agent/hermes",+ "--state-dir",+ str(tmp_path),+ ],+ db_path,+ )+ is False+ )++ def test_pure_other_home_is_scoped_elsewhere(self, tmp_path):+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ DEMO_HOME_ARGV, db_path+ )+ is True+ )+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ DEMO_VENV_ARGV, db_path+ )+ is True+ )++ def test_other_home_state_db_token_is_scoped_elsewhere(self, tmp_path):+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ ["hermes", "vacuum", "/home/demo/.hermes/state.db"], db_path+ )+ is True+ )++ def test_our_db_path_token_keeps_flag(self, tmp_path):+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ ["/home/demo/.hermes/hermes-agent/hermes", str(db_path)], db_path+ )+ is False+ )++ def test_our_shm_sidecar_token_keeps_flag(self, tmp_path):+ db_path = tmp_path / "state.db"+ assert (+ hermes_state_holders._argv_scoped_to_other_home(+ ["python3", "run_agent.py", f"{db_path}-shm"], db_path+ )+ is False+ )