DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(marginnote4): one rule for where a library's store lives
Bingxi Zhao (Frank)0989dcbbd9b5
diff --git a/deeptutor/api/routers/marginnote4.py b/deeptutor/api/routers/marginnote4.pyindex d433dfc27..c0d1efd7d 100644--- a/deeptutor/api/routers/marginnote4.py+++ b/deeptutor/api/routers/marginnote4.py@@ -26,7 +26,7 @@ from pydantic import BaseModel, Fieldfrom deeptutor.api.routers.auth import require_authfrom deeptutor.capabilities.marginnote4.models import MarginNoteObject, SyncBatch-from deeptutor.capabilities.marginnote4.store import MarginNoteStore, default_db_path+from deeptutor.capabilities.marginnote4.store import MarginNoteStore, resolve_db_pathfrom deeptutor.services.path_service import PathServicelogger = logging.getLogger(__name__)@@ -57,12 +57,12 @@ def _device_db_path(kb_name: str) -> Path:the store pairing wrote to, and gives :func:`pair_device` something tocheck itself against."""- return default_db_path(kb_name, path_service=PathService.get_instance())+ return resolve_db_path(kb_name, path_service=PathService.get_instance())def _store_for(request: Request) -> MarginNoteStore:"""Resolve (creating if absent) the store for a session-authenticated call."""- return MarginNoteStore(default_db_path(_requested_kb(request)))+ return MarginNoteStore(resolve_db_path(_requested_kb(request)))def _auth_device(request: Request, authorization: str | None) -> tuple[str, MarginNoteStore]:@@ -153,7 +153,7 @@ async def pair_device(body: PairRequest, request: Request) -> PairResponse:Returns a one-time token the Add-on stores and presents on every sync."""kb_name = _requested_kb(request)- if default_db_path(kb_name) != _device_db_path(kb_name):+ if resolve_db_path(kb_name) != _device_db_path(kb_name):# Pairing runs under a session and resolves the caller's own# workspace; /sync does not and resolves the default one. Where those# differ, pairing would hand out a token that 403s on every syncdiff --git a/deeptutor/capabilities/marginnote4/binding.py b/deeptutor/capabilities/marginnote4/binding.pyindex ee17c8cbb..f654ab06f 100644--- a/deeptutor/capabilities/marginnote4/binding.py+++ b/deeptutor/capabilities/marginnote4/binding.py@@ -36,13 +36,9 @@ def _resolve(context: UnifiedContext) -> dict[str, str] | None:meta = resolve_kb_metadata(ref)if not meta or meta.get("type") != MARGINNOTE4_KB_TYPE:continue- # The KB entry may carry an explicit ``db_path``; otherwise we derive- # one from the KB name so each connected library gets its own SQLite file.- db_path = str(meta.get("db_path") or "").strip()- if not db_path:- from deeptutor.capabilities.marginnote4.store import default_db_path+ from deeptutor.capabilities.marginnote4.store import resolve_db_path- db_path = str(default_db_path(ref))+ db_path = str(resolve_db_path(ref, metadata=meta))return {"name": str(meta.get("name") or ref), "db_path": db_path}return Nonediff --git a/deeptutor/capabilities/marginnote4/store.py b/deeptutor/capabilities/marginnote4/store.pyindex 72b3f347c..f2d7e60ec 100644--- a/deeptutor/capabilities/marginnote4/store.py+++ b/deeptutor/capabilities/marginnote4/store.py@@ -107,6 +107,41 @@ def default_db_path(kb_name: str, *, path_service: Any = None) -> Path:return path_service.user_data_dir / "marginnote4" / f"{safe}.db"+def resolve_db_path(+ kb_name: str,+ *,+ metadata: dict[str, Any] | None = None,+ path_service: Any = None,+) -> Path:+ """The store a connected MN4 library actually uses.++ A KB entry may pin ``db_path``; otherwise the path is derived from the name.+ That rule has three readers — the capability binding, the session endpoints+ that pair and list devices, and the device endpoints that sync — and a token+ issued against one store is invisible to a sync resolved against another, so+ it lives here rather than at each of them.++ Pass ``metadata`` when the caller already resolved the KB entry. Otherwise+ it is looked up, and a failure (no such KB, no request context) falls+ through to the derived path.+ """+ if metadata is None:+ metadata = _kb_metadata(kb_name)+ pinned = str((metadata or {}).get("db_path") or "").strip()+ if pinned:+ return Path(pinned)+ return default_db_path(kb_name, path_service=path_service)+++def _kb_metadata(kb_name: str) -> dict[str, Any] | None:+ try:+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ return resolve_kb_metadata(kb_name)+ except Exception: # noqa: BLE001 - unresolvable KB → derive from the name+ return None++class MarginNoteStore:"""CRUD + search over synced MN4 objects backed by SQLite.diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 55f2087c9..d1e3c1b55 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -1435,9 +1435,17 @@ class KnowledgeBaseManager:# reference the user's own external resource — or, for subagents, no# folder at all. Deleting one must only drop our pointer entry; never# touch what it references, and don't warn about the "missing" folder.- connected = is_connected_kb(config_kbs.get(name, {}))+ entry = config_kbs.get(name, {})+ connected = is_connected_kb(entry)if connected:dir_exists = False+ # One connected kind does own storage we created: a MarginNote library's+ # synced objects live in a SQLite file under our own data directory, not+ # in an external resource the user manages. Leaving it behind would also+ # resurrect every paired device the moment a library of the same name is+ # connected again.+ if entry.get("type") == MARGINNOTE4_KB_TYPE:+ self._delete_marginnote4_store(name, entry)if not confirm:# Ask for confirmation in CLI@@ -1495,6 +1503,27 @@ class KnowledgeBaseManager:self._save_config()return True+ def _delete_marginnote4_store(self, name: str, entry: dict) -> None:+ """Remove a MarginNote library's SQLite store, best-effort.++ A failure here must not strand the config entry: leaving the KB in the+ list is worse than an orphan file, exactly as for the index directory+ above.+ """+ from deeptutor.capabilities.marginnote4.store import resolve_db_path++ try:+ db_path = resolve_db_path(name, metadata=entry)+ db_path.unlink(missing_ok=True)+ # SQLite's WAL companions, when the last connection left them.+ for suffix in ("-wal", "-shm"):+ db_path.with_name(db_path.name + suffix).unlink(missing_ok=True)+ except Exception as exc: # noqa: BLE001 - orphan file beats a stuck entry+ logger.warning(+ f"Could not remove the MarginNote store for KB '{name}': {exc}. "+ "Continuing; the config entry is still cleaned up."+ )+def clean_rag_storage(self, name: str | None = None, backup: bool = True) -> bool:"""Clean (delete) index storage for a knowledge base.diff --git a/tests/capabilities/marginnote4/test_store.py b/tests/capabilities/marginnote4/test_store.pyindex 2fa7808b4..acf3ab6a1 100644--- a/tests/capabilities/marginnote4/test_store.py+++ b/tests/capabilities/marginnote4/test_store.py@@ -14,7 +14,12 @@ from deeptutor.capabilities.marginnote4.models import (MarginNoteObject,SyncBatch,)-from deeptutor.capabilities.marginnote4.store import MarginNoteStore+from deeptutor.capabilities.marginnote4.store import (+ MarginNoteStore,+ default_db_path,+ resolve_db_path,+)+from deeptutor.services.path_service import PathServicedef _seed_objects(device_id: str = "dev1") -> list[MarginNoteObject]:@@ -239,3 +244,32 @@ def test_cursor_advances(tmp_path: Path) -> None:cursor = store.get_cursor("dev1")assert cursor != ""assert cursor == result.new_cursor+++def test_resolve_db_path_prefers_a_pinned_entry(tmp_path, monkeypatch) -> None:+ """One rule, so a paired token stays findable by the sync that presents it.++ The capability binding, the pairing endpoints and the device endpoints all+ have to land on the same file. A KB may pin ``db_path``; everything else+ derives it from the name.+ """+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ try:+ pinned = tmp_path / "elsewhere" / "lib.db"+ assert resolve_db_path("Lib", metadata={"db_path": str(pinned)}) == pinned+ assert resolve_db_path("Lib", metadata={}) == default_db_path("Lib")+ # A blank pin is not a pin.+ assert resolve_db_path("Lib", metadata={"db_path": " "}) == default_db_path("Lib")+ finally:+ PathService.reset_instance()+++def test_resolve_db_path_derives_when_no_kb_is_resolvable(tmp_path, monkeypatch) -> None:+ """No request context and no such KB must not raise — just derive."""+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ try:+ assert resolve_db_path("Nonexistent") == default_db_path("Nonexistent")+ finally:+ PathService.reset_instance()diff --git a/tests/knowledge/test_marginnote4_kb.py b/tests/knowledge/test_marginnote4_kb.pyindex 418fc8cb2..0c4e6cae7 100644--- a/tests/knowledge/test_marginnote4_kb.py+++ b/tests/knowledge/test_marginnote4_kb.py@@ -12,6 +12,7 @@ import jsonfrom pathlib import Pathfrom deeptutor.knowledge.manager import KnowledgeBaseManager+from deeptutor.services.path_service import PathServicedef _seed_mn4(manager: KnowledgeBaseManager, name: str, db_path: str = "") -> None:@@ -109,3 +110,44 @@ def test_connected_kbs_backed_by_an_index_stay_retrievable() -> None:for kb_type in ("linked", "lightrag_server", "ima"):assert supports_rag_retrieval({"type": kb_type}) is True+++def test_deleting_the_kb_removes_its_synced_store(tmp_path: Path, monkeypatch) -> None:+ """The store is ours, unlike an Obsidian vault, so the delete claim holds.++ Leaving it behind would also resurrect every paired device the moment a+ library of the same name is connected again.+ """+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home"))+ PathService.reset_instance()+ try:+ from deeptutor.capabilities.marginnote4.store import MarginNoteStore, resolve_db_path++ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ manager.register_marginnote4_kb("Lib")+ db_path = resolve_db_path("Lib", metadata={})+ MarginNoteStore(db_path).pair_device(device_name="iPad")+ assert db_path.is_file()++ assert manager.delete_knowledge_base("Lib", confirm=True) is True+ assert not db_path.exists()+ assert "Lib" not in manager.config.get("knowledge_bases", {})+ finally:+ PathService.reset_instance()+++def test_deleting_an_obsidian_kb_leaves_its_vault_alone(tmp_path: Path) -> None:+ """The counter-case: an external resource the user manages is never touched."""+ vault = tmp_path / "vault"+ (vault / "notes").mkdir(parents=True)+ (vault / "notes" / "a.md").write_text("hi", encoding="utf-8")++ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ manager.config.setdefault("knowledge_bases", {})["Vault"] = {+ "type": "obsidian",+ "vault_path": str(vault),+ }+ manager._save_config()++ assert manager.delete_knowledge_base("Vault", confirm=True) is True+ assert (vault / "notes" / "a.md").is_file()