Skip to content

The agent that grows with you

fix(profiles): release memory-store handles before rmtree on profile delete

liuhao10244f354c27b749
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index bc8c8ea8d40..ad52b7b865e 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1614,6 +1614,22 @@ def delete_profile(name: str, yes: bool = False) -> Path:
# guard — resurrected the deleted tree.
_stop_profile_backends(canon, profile_dir)
+ # 2c. Release this process's holographic memory-store connections into
+ # the profile. The Desktop's *main* serve process opens memory_store.db
+ # for every known profile and is deliberately not stopped above, so on
+ # Windows its open handles make the rmtree below fail with WinError 32
+ # (#88347). When this delete runs inside serve (the DELETE
+ # /api/profiles/<name> route) the handles live in this process and are
+ # closed here; from the CLI this finds nothing and is a no-op.
+ try:
+ from plugins.memory.holographic.store import MemoryStore as _MemoryStore
+
+ _released = _MemoryStore.release_all_under(profile_dir)
+ if _released:
+ print(f"✓ Released {_released} memory-store connection(s) held by this process")
+ except Exception:
+ pass # best-effort: never block the delete on the release path
+
# 3. Remove wrapper script
if has_wrapper:
if remove_wrapper_script(canon):
diff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.py
index fcb193d4da2..34c857d0a0b 100644
--- a/plugins/memory/holographic/store.py
+++ b/plugins/memory/holographic/store.py
@@ -3,6 +3,7 @@ SQLite-backed fact store with entity resolution and trust scoring.
Single-user Hermes memory store plugin.
"""
+import os
import re
import sqlite3
import threading
@@ -616,6 +617,42 @@ class MemoryStore:
"""Convert a sqlite3.Row to a plain dict."""
return dict(row)
+ @classmethod
+ def release_all_under(cls, directory: "str | Path") -> int:
+ """Force-close every shared connection whose database lives under ``directory``.
+
+ ``close()`` is refcount-driven, so a live holder (e.g. an agent's
+ memory provider) keeps a profile's SQLite handle open indefinitely.
+ That is exactly what a profile delete must break on Windows: the
+ desktop's main ``serve`` process opens ``memory_store.db`` for every
+ known profile, and ``rmtree`` of the profile directory fails with
+ ``WinError 32`` while any of those handles is open (#88347). This
+ closes the matching connections unconditionally — the directory is
+ going away, so later use by a stale holder is expected to fail — and
+ returns how many were closed. In a process that holds none (e.g. the
+ CLI deleting from outside serve) this is a harmless no-op returning 0.
+ """
+ root = os.path.normcase(str(Path(directory).expanduser().resolve())) + os.sep
+ with cls._shared_guard:
+ # Snapshot the keys first so the registry stays stable while
+ # connections are closed inside their per-database locks (closing
+ # can run no user code, but this keeps the invariant obvious).
+ doomed = [
+ key
+ for key in cls._shared
+ if os.path.normcase(key).startswith(root)
+ ]
+ for key in doomed:
+ entry = cls._shared.pop(key)
+ try:
+ with entry["lock"]:
+ entry["conn"].close()
+ except Exception:
+ # A connection that is already closed or broken must not
+ # abort releasing its siblings.
+ pass
+ return len(doomed)
+
def close(self) -> None:
"""Release this instance's reference to the shared connection.
diff --git a/tests/plugins/memory/test_holographic_shutdown_closes_db.py b/tests/plugins/memory/test_holographic_shutdown_closes_db.py
index 7917be6c8cb..436d0d2ceb0 100644
--- a/tests/plugins/memory/test_holographic_shutdown_closes_db.py
+++ b/tests/plugins/memory/test_holographic_shutdown_closes_db.py
@@ -46,3 +46,48 @@ def test_shutdown_closes_store_connection(tmp_path):
conn.execute("SELECT 1")
+def test_release_all_under_closes_connections_inside_directory_only(tmp_path):
+ """Regression test for #88347 — profile delete must break refcounted handles.
+
+ ``close()`` alone can never free a database held by a live agent (refs >= 1),
+ and on Windows an open SQLite handle makes rmtree of the profile directory
+ fail with WinError 32. ``release_all_under`` force-closes exactly the shared
+ connections under the doomed directory and leaves everything else alone.
+ """
+ from plugins.memory.holographic.store import MemoryStore
+
+ profile_dir = tmp_path / "profiles" / "default-2"
+ profile_dir.mkdir(parents=True)
+ inside = MemoryStore(db_path=profile_dir / "memory_store.db", hrr_dim=64)
+ outside = MemoryStore(db_path=tmp_path / "other" / "memory_store.db", hrr_dim=64)
+ inside_conn = inside._conn
+ outside_conn = outside._conn
+ # Both live before the release; the inside one is held "forever" (refs=1,
+ # like a live agent's provider — nobody calls close()).
+ inside_conn.execute("SELECT 1").fetchone()
+ outside_conn.execute("SELECT 1").fetchone()
+
+ try:
+ released = MemoryStore.release_all_under(profile_dir)
+ assert released == 1
+
+ # The doomed connection is really closed despite refs > 0 ...
+ with pytest.raises(sqlite3.ProgrammingError):
+ inside_conn.execute("SELECT 1")
+ # ... and the registry entry is gone, so a second release finds
+ # nothing (the CLI-process no-op case).
+ assert str((profile_dir / "memory_store.db").resolve()) not in MemoryStore._shared
+ assert MemoryStore.release_all_under(profile_dir) == 0
+ # A new store on the same path reopens fresh instead of reusing
+ # the dead connection.
+ reopened = MemoryStore(db_path=profile_dir / "memory_store.db", hrr_dim=64)
+ reopened._conn.execute("SELECT 1").fetchone()
+
+ # The sibling outside the directory is untouched.
+ outside_conn.execute("SELECT 1").fetchone()
+ finally:
+ inside.close()
+ reopened.close()
+ outside.close()
+
+