Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(marginnote4): stop two libraries from claiming one store

Bingxi Zhao (Frank)081a73a15cd7
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index d1e3c1b55..23ee4bc4f 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -907,7 +907,8 @@ class KnowledgeBaseManager:
the MarginNote capability binds to. When ``db_path`` is omitted the
capability derives a default SQLite path from the KB name, so callers
can leave it blank for the simple single-library case. Raises
- ``ValueError`` on a missing name or a name clash.
+ ``ValueError`` on a missing name, a name clash, or a store already
+ claimed by another library.
"""
name = (name or "").strip()
if not name:
@@ -918,6 +919,18 @@ class KnowledgeBaseManager:
if name in knowledge_bases:
raise ValueError(f"A knowledge base named '{name}' already exists.")
+ db_path = (db_path or "").strip()
+ claimed_by = self._marginnote4_store_owner(name, db_path, knowledge_bases)
+ if claimed_by:
+ # Distinct names can still derive one store: the default path keeps
+ # only alphanumerics, `-` and `_`, so "My Lib" and "My/Lib" both
+ # land on My_Lib.db. Sharing it would merge two libraries' objects
+ # and let either one's devices sync into the other.
+ raise ValueError(
+ f"Knowledge base '{claimed_by}' already uses that MarginNote store. "
+ "Pick a name that differs by more than punctuation."
+ )
+
now = datetime.now().isoformat()
entry: dict[str, Any] = {
"path": name,
@@ -928,13 +941,32 @@ class KnowledgeBaseManager:
"created_at": now,
"updated_at": now,
}
- db_path = (db_path or "").strip()
if db_path:
entry["db_path"] = db_path
knowledge_bases[name] = entry
self._save_config()
return entry
+ @staticmethod
+ def _marginnote4_store_owner(
+ name: str,
+ db_path: str,
+ knowledge_bases: dict[str, Any],
+ ) -> str | None:
+ """Name of the MarginNote library already using this store, if any."""
+ from deeptutor.capabilities.marginnote4.store import resolve_db_path
+
+ def _store(kb_name: str, entry: dict) -> Path:
+ return resolve_db_path(kb_name, metadata=entry).expanduser().resolve()
+
+ wanted = _store(name, {"db_path": db_path})
+ for other_name, other in knowledge_bases.items():
+ if not isinstance(other, dict) or other.get("type") != MARGINNOTE4_KB_TYPE:
+ continue
+ if _store(other_name, other) == wanted:
+ return other_name
+ return None
+
def register_ima_kb(
self,
name: str,
diff --git a/tests/knowledge/test_marginnote4_kb.py b/tests/knowledge/test_marginnote4_kb.py
index 0c4e6cae7..869a19f95 100644
--- a/tests/knowledge/test_marginnote4_kb.py
+++ b/tests/knowledge/test_marginnote4_kb.py
@@ -11,6 +11,8 @@ from __future__ import annotations
import json
from pathlib import Path
+import pytest
+
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.services.path_service import PathService
@@ -151,3 +153,42 @@ def test_deleting_an_obsidian_kb_leaves_its_vault_alone(tmp_path: Path) -> None:
assert manager.delete_knowledge_base("Vault", confirm=True) is True
assert (vault / "notes" / "a.md").is_file()
+
+
+def test_register_rejects_a_name_that_derives_an_existing_store(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Distinct names can still derive one SQLite file.
+
+ ``default_db_path`` keeps only alphanumerics, ``-`` and ``_``, so "My Lib"
+ and "My/Lib" both land on ``My_Lib.db``. Sharing it would merge two
+ libraries' objects and let either one's paired devices sync into the other.
+ """
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home"))
+ PathService.reset_instance()
+ try:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_marginnote4_kb("My Lib")
+
+ with pytest.raises(ValueError, match="already uses that MarginNote store"):
+ manager.register_marginnote4_kb("My/Lib")
+
+ # A name that differs by more than punctuation is fine.
+ manager.register_marginnote4_kb("Other Lib")
+ assert set(manager.config["knowledge_bases"]) == {"My Lib", "Other Lib"}
+ finally:
+ PathService.reset_instance()
+
+
+def test_register_rejects_a_pinned_path_another_library_owns(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path / "home"))
+ PathService.reset_instance()
+ try:
+ shared = tmp_path / "stores" / "shared.db"
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_marginnote4_kb("First", db_path=str(shared))
+
+ with pytest.raises(ValueError, match="already uses that MarginNote store"):
+ manager.register_marginnote4_kb("Second", db_path=str(shared))
+ finally:
+ PathService.reset_instance()