DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(knowledge): add MarginNote 4 as a connected knowledge base (#931)
evan188199-tech1413cd8ed0c7
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 885bc7f81..c3475a623 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -353,6 +353,7 @@ from deeptutor.api.routers import (dashboard,imports,knowledge,+ marginnote4,mastery_path,mcp_settings,memory,@@ -506,6 +507,14 @@ app.include_router(dependencies=_auth,)+# MarginNote 4 device bridge — pairing/management routes carry _auth in-router;+# sync/heartbeat use device-token auth (the Add-on has no session).+app.include_router(+ marginnote4.router,+ prefix="/api/v1/marginnote4",+ tags=["marginnote4"],+)+# Unified WebSocket endpoint — auth is checked inside the handler (WebSockets# cannot use FastAPI dependencies in the standard way)app.include_router(unified_ws.router, prefix="/api/v1", tags=["unified-ws"])diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 1a968b058..f3a247df9 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -1729,6 +1729,41 @@ async def connect_obsidian_vault(payload: ConnectObsidianRequest):raise HTTPException(status_code=500, detail=str(e))+class ConnectMarginNote4Request(BaseModel):+ name: str+ db_path: str = ""+ description: str = ""++[email protected]("/connect-marginnote4")+async def connect_marginnote4(payload: ConnectMarginNote4Request):+ """Register a connected MarginNote 4 library as a knowledge base.++ Creates a ``type: marginnote4`` pointer so the MarginNote capability can+ bind to it on turns where the user selects this KB. When ``db_path`` is+ omitted the capability derives a default SQLite path from the KB name.+ """+ name = (payload.name or "").strip()+ if not name:+ raise HTTPException(status_code=400, detail="name is required.")+ try:+ manager = get_kb_manager()+ entry = manager.register_marginnote4_kb(+ name,+ db_path=(payload.db_path or "").strip(),+ description=(payload.description or "").strip(),+ )+ result = {"status": "connected", "name": name}+ if entry.get("db_path"):+ result["db_path"] = entry["db_path"]+ return result+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))+ except Exception as e:+ logger.error(f"Error connecting MarginNote 4 library: {e}")+ raise HTTPException(status_code=500, detail=str(e))++class ProbeFolderRequest(BaseModel):folder_path: strrag_provider: str = DEFAULT_PROVIDERdiff --git a/deeptutor/api/routers/marginnote4.py b/deeptutor/api/routers/marginnote4.pynew file mode 100644index 000000000..61d83d62e--- /dev/null+++ b/deeptutor/api/routers/marginnote4.py@@ -0,0 +1,238 @@+"""HTTP bridge for MarginNote 4 Add-on devices.++The MN4 Add-on (JavaScript running inside MarginNote 4) calls these endpoints+to pair with this DeepTutor instance and push synced study data.++Authentication layers:+* ``/pair``, ``/devices``, ``/status`` -- DeepTutor session auth (the logged-in+ user manages their own devices). The router is mounted with ``_auth`` in+ ``main.py``.+* ``/sync``, ``/heartbeat`` -- device-token auth via+ ``Authorization: MarginNote <device_id>:<token>``. The Add-on stores the+ token received at pairing time.++Phase 1 scope: device pairing, incremental sync, heartbeat. Write-back to MN4+(propose / apply / verify) is Phase 2.+"""++from __future__ import annotations++import logging+from typing import Any++from fastapi import APIRouter, Depends, Header, HTTPException, Request+from pydantic import BaseModel, Field++from deeptutor.api.routers.auth import require_auth+from deeptutor.capabilities.marginnote4.models import MarginNoteObject, SyncBatch+from deeptutor.capabilities.marginnote4.store import MarginNoteStore++logger = logging.getLogger(__name__)+router = APIRouter()+_auth = [Depends(require_auth)]+++def _store_for(request: Request) -> MarginNoteStore:+ """Resolve the MarginNote store from request context.++ In Phase 1, a single default store serves all devices. When a KB name is+ passed via the ``X-MN4-KB`` header, its dedicated database is used instead.+ """+ kb_name = request.headers.get("x-mn4-kb", "default")+ from deeptutor.capabilities.marginnote4.store import _default_db_path++ db_path = _default_db_path(kb_name)+ return MarginNoteStore(db_path)+++def _auth_device(request: Request, authorization: str | None) -> tuple[str, MarginNoteStore]:+ """Validate the device token and return ``(device_id, store)``."""+ if not authorization or not authorization.startswith("MarginNote "):+ raise HTTPException(401, "Missing or malformed Authorization header.")+ raw = authorization[len("MarginNote ") :]+ if ":" not in raw:+ raise HTTPException(401, "Invalid Authorization format.")+ device_id, token = raw.split(":", 1)+ store = _store_for(request)+ if not store.verify_token(device_id, token):+ raise HTTPException(403, "Invalid device credentials.")+ store.touch_device(device_id)+ return device_id, store+++# -- request / response models ---------------------------------------------+++class PairRequest(BaseModel):+ device_name: str = ""+ device_kind: str = "macos"+++class PairResponse(BaseModel):+ device_id: str+ token: str+ device_name: str+ device_kind: str+++class SyncObjectIn(BaseModel):+ object_id: str+ object_type: str+ title: str = ""+ content: str = ""+ excerpt: str | None = None+ document_id: str | None = None+ document_title: str | None = None+ page: int | None = None+ tags: list[str] = Field(default_factory=list)+ links: list[str] = Field(default_factory=list)+ color: str | None = None+ created_at: str = ""+ updated_at: str = ""+ raw: dict[str, Any] = Field(default_factory=dict)+++class SyncRequest(BaseModel):+ cursor: str = ""+ objects: list[SyncObjectIn] = Field(default_factory=list)+ deleted_ids: list[str] = Field(default_factory=list)+++class SyncResponse(BaseModel):+ stored: int+ updated: int+ deleted: int+ new_cursor: str+++class DeviceInfo(BaseModel):+ device_id: str+ device_name: str+ device_kind: str+ paired_at: str+ last_seen: str+ active: bool+++# -- session-authenticated endpoints (DeepTutor user) -----------------------++[email protected]("/pair", response_model=PairResponse, dependencies=_auth)+async def pair_device(body: PairRequest, request: Request) -> PairResponse:+ """Pair a new MN4 device. Requires a DeepTutor session.++ Returns a one-time token the Add-on stores and presents on every sync.+ """+ store = _store_for(request)+ device, token = store.pair_device(device_name=body.device_name, device_kind=body.device_kind)+ logger.info("Paired MN4 device %s (%s)", device.device_id, device.device_name)+ return PairResponse(+ device_id=device.device_id,+ token=token,+ device_name=device.device_name,+ device_kind=device.device_kind,+ )++[email protected]("/devices", response_model=list[DeviceInfo], dependencies=_auth)+async def list_devices(request: Request) -> list[DeviceInfo]:+ """List all paired devices."""+ store = _store_for(request)+ return [+ DeviceInfo(+ device_id=d.device_id,+ device_name=d.device_name,+ device_kind=d.device_kind,+ paired_at=d.paired_at,+ last_seen=d.last_seen,+ active=d.active,+ )+ for d in store.list_devices()+ ]++[email protected]("/devices/{device_id}", dependencies=_auth)+async def revoke_device(device_id: str, request: Request) -> dict[str, str]:+ """Revoke a paired device."""+ store = _store_for(request)+ if not store.revoke_device(device_id):+ raise HTTPException(404, f"Device {device_id} not found.")+ return {"status": "revoked", "device_id": device_id}++[email protected]("/status", dependencies=_auth)+async def status(request: Request) -> dict[str, Any]:+ """Health check and summary stats."""+ store = _store_for(request)+ return {+ "status": "ok",+ "devices": len(store.list_devices()),+ "objects": store.count(),+ }+++# -- device-token-authenticated endpoints (MN4 Add-on) ---------------------++[email protected]("/sync", response_model=SyncResponse)+async def sync_objects(+ body: SyncRequest,+ request: Request,+ authorization: str | None = Header(None),+) -> SyncResponse:+ """Receive an incremental sync batch from a paired MN4 device."""+ device_id, store = _auth_device(request, authorization)+ objects = [+ MarginNoteObject(+ object_id=o.object_id,+ object_type=o.object_type,+ title=o.title,+ content=o.content,+ excerpt=o.excerpt,+ document_id=o.document_id,+ document_title=o.document_title,+ page=o.page,+ tags=o.tags,+ links=o.links,+ color=o.color,+ created_at=o.created_at,+ updated_at=o.updated_at,+ device_id=device_id,+ raw=o.raw,+ )+ for o in body.objects+ ]+ batch = SyncBatch(+ device_id=device_id,+ cursor=body.cursor,+ objects=objects,+ deleted_ids=body.deleted_ids,+ )+ result = store.ingest(batch)+ logger.info(+ "MN4 sync from %s: +%d ~%d -%d",+ device_id,+ result.stored,+ result.updated,+ result.deleted,+ )+ return SyncResponse(+ stored=result.stored,+ updated=result.updated,+ deleted=result.deleted,+ new_cursor=result.new_cursor,+ )++[email protected]("/heartbeat")+async def heartbeat(+ request: Request,+ authorization: str | None = Header(None),+) -> dict[str, Any]:+ """Lightweight liveness check. Updates last_seen for the device."""+ device_id, store = _auth_device(request, authorization)+ return {+ "status": "ok",+ "device_id": device_id,+ "object_count": store.count(device_id=device_id),+ }diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 65be67fd8..b72307961 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -342,8 +342,10 @@ class SourceExplorer(BaseAgent):"""Split *kb_list* into (retrievable, unreachable).Only the KBs ``rag_search`` genuinely cannot reach are set aside: an- Obsidian vault (no index — its capability navigates live files) and a- connected subagent (not a document collection). Sweeping those returned+ Obsidian vault (no index — its capability navigates live files), a+ MarginNote 4 library (same shape: synced objects in their own store,+ reachable only through the MN4 tools) and a connected subagent (not a+ document collection). Sweeping those returnednothing and looked identical to a source that simply had no relevantcontent, so the reader never learned their vault contributed zero;reaching them properly means driving each capability, which is separatediff --git a/deeptutor/capabilities/marginnote4/__init__.py b/deeptutor/capabilities/marginnote4/__init__.pynew file mode 100644index 000000000..114fa7f46--- /dev/null+++ b/deeptutor/capabilities/marginnote4/__init__.py@@ -0,0 +1,13 @@+"""MarginNote 4 loop capability -- agentic retrieval over a synced MN4 library."""++from deeptutor.capabilities.marginnote4.capability import MarginNoteCapability+from deeptutor.capabilities.marginnote4.tools import (+ MARGINNOTE_TOOL_NAMES,+ MARGINNOTE_TOOL_TYPES,+)++__all__ = [+ "MARGINNOTE_TOOL_NAMES",+ "MARGINNOTE_TOOL_TYPES",+ "MarginNoteCapability",+]diff --git a/deeptutor/capabilities/marginnote4/binding.py b/deeptutor/capabilities/marginnote4/binding.pynew file mode 100644index 000000000..fecfdad25--- /dev/null+++ b/deeptutor/capabilities/marginnote4/binding.py@@ -0,0 +1,69 @@+"""Resolve which connected MarginNote 4 library (if any) the current turn targets.++Mirrors the Obsidian binding pattern: the first selected KB whose metadata is+``type == marginnote4`` wins. The KB's ``db_path`` (or a computed default)+becomes the live store the MarginNote tools query. The result is cached on+``context.metadata`` so ``is_active`` / ``augment_kwargs`` / ``system_block``+share a single resolution.+"""++from __future__ import annotations++from deeptutor.core.context import UnifiedContext+from deeptutor.knowledge.kb_types import MARGINNOTE4_KB_TYPE++_CACHE_KEY = "_marginnote4_binding"+_UNSET = object()+++def marginnote_binding(context: UnifiedContext) -> dict[str, str] | None:+ """Return ``{"name", "db_path"}`` of the selected MN4 KB, or ``None``."""+ cached = context.metadata.get(_CACHE_KEY, _UNSET)+ if cached is not _UNSET:+ return cached or None+ resolved = _resolve(context)+ context.metadata[_CACHE_KEY] = resolved or ""+ return resolved+++def _resolve(context: UnifiedContext) -> dict[str, str] | None:+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ for ref in context.knowledge_bases or []:+ ref = str(ref).strip()+ if not ref:+ continue+ 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++ db_path = str(_default_db_path(ref))+ return {"name": str(meta.get("name") or ref), "db_path": db_path}+ return None+++def marginnote_kb_refs(context: UnifiedContext) -> set[str]:+ """Return every selected KB ref that resolves to a connected MN4 library.++ All MN4 refs are reported so the chat pipeline can exclude them from the+ ``rag`` surface, exactly like Obsidian vault refs.+ """+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ refs: set[str] = set()+ for ref in context.knowledge_bases or []:+ ref = str(ref).strip()+ if not ref:+ continue+ meta = resolve_kb_metadata(ref)+ if meta and meta.get("type") == MARGINNOTE4_KB_TYPE:+ refs.add(ref)+ return refs+++__all__ = ["marginnote_binding", "marginnote_kb_refs"]diff --git a/deeptutor/capabilities/marginnote4/capability.py b/deeptutor/capabilities/marginnote4/capability.pynew file mode 100644index 000000000..835b83f6b--- /dev/null+++ b/deeptutor/capabilities/marginnote4/capability.py@@ -0,0 +1,88 @@+"""MarginNote 4 loop capability -- agentic retrieval over a synced MN4 library.++Active whenever the user's selected knowledge base is a connected MarginNote 4+library (resolved by :mod:`deeptutor.capabilities.marginnote4.binding`). As a+:class:`KnowledgeCapability` it owns the turn: the chat loop runs exclusively+on the seven MarginNote tools (plus the ``ask_user`` floor), navigating the+synced study data rather than retrieving flattened RAG chunks.++The store path is injected into each tool call as ``_db_path`` server-side;+the model never supplies it.+"""++from __future__ import annotations++from importlib import resources+from typing import Any++from deeptutor.capabilities.marginnote4.binding import (+ marginnote_binding,+ marginnote_kb_refs,+)+from deeptutor.capabilities.marginnote4.tools import MARGINNOTE_TOOL_NAMES+from deeptutor.capabilities.protocol import KnowledgeCapability, PromptBlock+from deeptutor.core.context import UnifiedContext+++class MarginNoteCapability(KnowledgeCapability):+ """Turn-scoped integration for a connected MarginNote 4 library."""++ name = "marginnote4"+ owned_tools = MARGINNOTE_TOOL_NAMES++ def is_active(self, context: UnifiedContext) -> bool:+ return marginnote_binding(context) is not None++ def owned_kbs(self, context: UnifiedContext) -> set[str]:+ return marginnote_kb_refs(context)++ def system_block(+ self,+ context: UnifiedContext,+ *,+ language: str,+ prompts: dict[str, Any],+ ) -> PromptBlock | None:+ binding = marginnote_binding(context)+ if binding is None:+ return None+ override = _prompt_text(prompts, ("marginnote4", "system"))+ content = override or _load_system_prompt(language)+ return PromptBlock("marginnote4", content.replace("{library_name}", binding["name"]))++ def augment_kwargs(+ self,+ tool_name: str,+ kwargs: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ if tool_name not in MARGINNOTE_TOOL_NAMES:+ return kwargs+ binding = marginnote_binding(context)+ if binding is None:+ return kwargs+ updated = dict(kwargs)+ updated["_db_path"] = binding["db_path"]+ return updated++ def pre_loop_seed(self, context: UnifiedContext) -> str:+ _ = context+ return ""+++def _prompt_text(prompts: dict[str, Any], path: tuple[str, ...]) -> str:+ value: Any = prompts+ for key in path:+ if not isinstance(value, dict):+ return ""+ value = value.get(key)+ return value if isinstance(value, str) and value else ""+++def _load_system_prompt(language: str) -> str:+ lang = "zh" if language.lower().startswith("zh") else "en"+ prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")+ return prompt.read_text(encoding="utf-8").strip()+++__all__ = ["MarginNoteCapability"]diff --git a/deeptutor/capabilities/marginnote4/models.py b/deeptutor/capabilities/marginnote4/models.pynew file mode 100644index 000000000..fe047d909--- /dev/null+++ b/deeptutor/capabilities/marginnote4/models.py@@ -0,0 +1,173 @@+"""Core data models for the MarginNote 4 bridge.++These types describe MN4 objects as they land in DeepTutor after sync.+The MN4 Add-on serialises its native objects (notes, excerpts, cards, mindmap+nodes, documents) into :class:`MarginNoteObject` rows that the sync store+indexes and the capability tools query.++Design notes+------------+* Every object carries a stable ``object_id`` derived from MN4's internal ID,+ so re-syncs update in place instead of creating duplicates.+* Text fields (``title``, ``excerpt``, ``content``) are plain strings — no+ HTML or MN4 markup. The Add-on is responsible for flattening rich text.+* ``raw`` preserves the original MN4 JSON for fields DeepTutor does not model+ yet, so the schema can grow without re-syncing.+* ``device_id`` ties each object to the paired device that synced it, so a+ user with multiple devices can tell which copy is authoritative.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass, field+from typing import Any++# --------------------------------------------------------------------------- #+# Object types — what kind of MN4 entity a row represents.+# --------------------------------------------------------------------------- #++NOTE = "note" # A highlight, underline, or text selection annotation.+EXCERPT = "excerpt" # An excerpt block (longer quoted passage).+CARD = "card" # A flashcard with front/back.+MINDMAP_NODE = "mindmap_node" # A node in the study mindmap.+DOCUMENT = "document" # A source document (PDF, EPUB, web).+COMMENT = "comment" # A free-form comment attached to a note or node.++ALL_TYPES: frozenset[str] = frozenset({NOTE, EXCERPT, CARD, MINDMAP_NODE, DOCUMENT, COMMENT})+++@dataclass(slots=True)+class MarginNoteObject:+ """One synced MarginNote 4 entity.++ Attributes:+ object_id: Stable ID from MN4 (its internal ``noteId`` / ``nodeId``).+ object_type: One of :data:`ALL_TYPES`.+ title: Display title (note title, card title, node text, doc title).+ content: Primary text body. For a card this is the front; for an+ annotation it is the excerpt text; for a mindmap node it is the+ node's text content.+ excerpt: Quoted source text (the highlighted passage), when the object+ is anchored to a document. ``None`` for cards without a source.+ document_id: ID of the source document, when the object belongs to one.+ document_title: Human-readable title of the source document.+ page: Page number in the source document, when known.+ tags: User-assigned tags.+ links: IDs of linked MN4 objects (parent/child in mindmap,+ linked cards, etc.).+ color: MN4 highlight colour label, when applicable.+ created_at: ISO-8601 timestamp from MN4.+ updated_at: ISO-8601 timestamp from MN4 (last modification).+ synced_at: ISO-8601 timestamp when DeepTutor received this version.+ device_id: The paired device that synced this object.+ raw: Original MN4 JSON payload, preserved verbatim for forward compat.+ """++ object_id: str+ object_type: str+ title: str = ""+ content: str = ""+ excerpt: str | None = None+ document_id: str | None = None+ document_title: str | None = None+ page: int | None = None+ tags: list[str] = field(default_factory=list)+ links: list[str] = field(default_factory=list)+ color: str | None = None+ created_at: str = ""+ updated_at: str = ""+ synced_at: str = ""+ device_id: str = ""+ raw: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ """Serialise to a plain dict for JSON responses and storage."""+ return asdict(self)+++@dataclass(slots=True)+class SyncBatch:+ """A batch of objects pushed by a device during incremental sync.++ Attributes:+ device_id: The paired device pushing this batch.+ cursor: Monotonic sync position this batch advances from.+ objects: New or updated objects since the previous cursor.+ deleted_ids: IDs tombstoned since the previous cursor.+ """++ device_id: str+ cursor: str = ""+ objects: list[MarginNoteObject] = field(default_factory=list)+ deleted_ids: list[str] = field(default_factory=list)+++@dataclass(slots=True)+class SyncResult:+ """Outcome of ingesting a :class:`SyncBatch` into the store."""++ stored: int = 0+ updated: int = 0+ deleted: int = 0+ new_cursor: str = ""+++@dataclass(slots=True)+class PairedDevice:+ """A MarginNote 4 device registered with this DeepTutor instance.++ Attributes:+ device_id: Stable identifier generated at pairing time.+ device_name: Human-readable label (e.g. "MacBook Pro", "iPad").+ device_kind: ``macos`` or ``ipados``.+ paired_at: ISO-8601 timestamp.+ last_seen: ISO-8601 timestamp of last sync or heartbeat.+ active: Whether the device is currently enabled.+ """++ device_id: str+ device_name: str = ""+ device_kind: str = "macos"+ paired_at: str = ""+ last_seen: str = ""+ active: bool = True+++@dataclass(slots=True)+class LearningEvent:+ """A study event observed on the MN4 side (Phase 3).++ Captures a review or study interaction so DeepTutor can track mastery+ without touching MN4's private FSRS scheduling data.++ Attributes:+ event_id: Unique event identifier.+ object_id: The MN4 object studied (usually a card).+ event_type: ``review``, ``study``, ``flag``, ``confidence``.+ outcome: ``again``, ``hard``, ``good``, ``easy`` (or free text).+ timestamp: ISO-8601.+ device_id: Device that observed the event.+ """++ event_id: str+ object_id: str+ event_type: str = "review"+ outcome: str = ""+ timestamp: str = ""+ device_id: str = ""+++__all__ = [+ "ALL_TYPES",+ "CARD",+ "COMMENT",+ "DOCUMENT",+ "EXCERPT",+ "LearningEvent",+ "MINDMAP_NODE",+ "NOTE",+ "MarginNoteObject",+ "PairedDevice",+ "SyncBatch",+ "SyncResult",+]diff --git a/deeptutor/capabilities/marginnote4/prompts/en/system.md b/deeptutor/capabilities/marginnote4/prompts/en/system.mdnew file mode 100644index 000000000..6e8f08117--- /dev/null+++ b/deeptutor/capabilities/marginnote4/prompts/en/system.md@@ -0,0 +1,54 @@+# MarginNote 4 Library++You are connected to the user's MarginNote 4 library **{library_name}** -- study+data synced from MarginNote 4, a reading and study app for PDFs, EPUBs, and web+articles. The library contains five kinds of objects:++- **notes**: highlights and annotations the user made while reading+- **excerpts**: longer quoted passages from source documents+- **cards**: flashcards with a front (question) and back (answer)+- **mindmap_nodes**: nodes in the study mindmap that organize knowledge+- **documents**: source PDFs, books, and articles the user studies from++Every object may link to related objects (a note links to its card, a mindmap+node links to its children). Follow these links to surface connections a flat+search would miss.++This turn you work *only* with the MarginNote tools; there is no web, code, or+other knowledge base. The synced library is the source of truth.++## Retrieving (answering from the library)++Don't guess -- explore. A typical path:++1. `marginnote_search` for the topic, or `marginnote_tags` /+ `marginnote_documents` to map the library when you lack a search term.+2. `marginnote_read` the promising objects for full content.+3. Follow the graph: `marginnote_links` surfaces related notes and cards a+ keyword search misses.+4. Answer grounded in what you read, citing document titles and page numbers.+ If the library doesn't cover it, say so rather than inventing.++## Tips for good answers++- When you find a relevant note, check `marginnote_links` to discover the card+ it generated and the mindmap node it belongs to -- this gives the full study+ context.+- If the user asks "what do I know about X", search for X, then read the top+ results and summarize the connections between them.+- If the user wants to review, use `marginnote_cards` to pull flashcards and+ walk through them interactively.+- Page numbers and document titles are your citation anchors -- always include+ them so the user can find the source in MarginNote 4.++## Study material++- `marginnote_cards` lists flashcards. When the user wants to review or study,+ pull the relevant cards and walk through them one by one.+- `marginnote_list` with `object_type=mindmap_node` shows the mindmap structure+ -- useful for understanding how the user organizes their knowledge.++## Writing (Phase 2 -- not yet available)++Writing back to MarginNote 4 is not available yet. If the user asks to create or+modify notes in MN4, suggest they do it directly in the app for now.diff --git a/deeptutor/capabilities/marginnote4/prompts/zh/system.md b/deeptutor/capabilities/marginnote4/prompts/zh/system.mdnew file mode 100644index 000000000..79d0643aa--- /dev/null+++ b/deeptutor/capabilities/marginnote4/prompts/zh/system.md@@ -0,0 +1,44 @@+# MarginNote 4 学习库++你已连接到用户的 MarginNote 4 学习库 **{library_name}** -- 这是从 MarginNote 4+(一款用于 PDF、EPUB 和网页文章的阅读与学习应用)同步的学习数据。学习库包含五种对象:++- **note(笔记)**:用户阅读时做的高亮和批注+- **excerpt(摘录)**:从源文档中摘录的较长段落+- **card(卡片)**:带有正面(问题)和背面(答案)的抽认卡+- **mindmap_node(思维导图节点)**:学习思维导图中组织知识的节点+- **document(文档)**:用户学习的源 PDF、书籍和文章++每个对象都可能链接到相关对象(一条笔记链接到它生成的卡片,一个思维导图节点链接到其子节点)。+追踪这些链接,发现扁平搜索会遗漏的知识关联。++本轮你*只*使用 MarginNote 工具;没有网络搜索、代码或其他知识库。同步的学习库是唯一的数据来源。++## 检索(从学习库中回答)++不要猜测 -- 先探索。典型路径:++1. 用 `marginnote_search` 搜索主题,或在没有搜索词时用 `marginnote_tags` /+ `marginnote_documents` 浏览学习库结构。+2. 用 `marginnote_read` 读取感兴趣的对象的完整内容。+3. 追踪知识图谱:`marginnote_links` 能发现关键词搜索遗漏的相关笔记和卡片。+4. 基于你读到的内容回答,引用文档标题和页码。如果学习库中没有覆盖,如实说明。++## 回答技巧++- 找到一条相关笔记后,用 `marginnote_links` 查看它关联的卡片和所属的思维导图节点 -- 这能+ 给出完整的学习上下文。+- 当用户问"我对 X 了解什么"时,搜索 X,然后读取前几条结果,总结它们之间的联系。+- 当用户想复习时,用 `marginnote_cards` 调取抽认卡,逐张讲解。+- 页码和文档标题是你的引用锚点 -- 始终包含它们,让用户能在 MarginNote 4 中找到原文。++## 学习材料++- `marginnote_cards` 列出抽认卡。当用户想要复习或学习时,调取相关卡片并逐一讲解。+- `marginnote_list`(`object_type=mindmap_node`)展示思维导图结构 -- 有助于了解用户如何+ 组织知识。++## 写回(第二阶段 -- 尚未实现)++向 MarginNote 4 写回功能尚未实现。如果用户要求在 MN4 中创建或修改笔记,建议暂时直接在+应用中操作。diff --git a/deeptutor/capabilities/marginnote4/store.py b/deeptutor/capabilities/marginnote4/store.pynew file mode 100644index 000000000..4784c3fd5--- /dev/null+++ b/deeptutor/capabilities/marginnote4/store.py@@ -0,0 +1,492 @@+"""SQLite-backed storage for synced MarginNote 4 objects.++This is the *only* module that knows the on-disk schema. Every other layer --+tools, capability, HTTP bridge -- goes through the public methods here.++Schema overview+---------------+* ``mn4_objects`` -- one row per synced MN4 entity, JSON payload in ``raw``.+* ``mn4_devices`` -- paired devices with hashed tokens.+* ``mn4_cursors`` -- per-device sync position.+* ``mn4_tombstones`` -- deleted object IDs (soft-delete for conflict resolution).++The database file lives under ``data/marginnote4/<kb_name>.db`` by default.+"""++from __future__ import annotations++from datetime import datetime, timezone+import hashlib+import json+import logging+from pathlib import Path+import secrets+import sqlite3+from typing import Any++from deeptutor.capabilities.marginnote4.models import (+ ALL_TYPES,+ MarginNoteObject,+ PairedDevice,+ SyncBatch,+ SyncResult,+)++logger = logging.getLogger(__name__)++_SCHEMA = """+CREATE TABLE IF NOT EXISTS mn4_objects (+ object_id TEXT NOT NULL,+ device_id TEXT NOT NULL,+ object_type TEXT NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ content TEXT NOT NULL DEFAULT '',+ excerpt TEXT,+ document_id TEXT,+ document_title TEXT,+ page INTEGER,+ tags TEXT NOT NULL DEFAULT '[]',+ links TEXT NOT NULL DEFAULT '[]',+ color TEXT,+ created_at TEXT NOT NULL DEFAULT '',+ updated_at TEXT NOT NULL DEFAULT '',+ synced_at TEXT NOT NULL DEFAULT '',+ raw TEXT NOT NULL DEFAULT '{}',+ PRIMARY KEY (object_id, device_id)+);++CREATE INDEX IF NOT EXISTS idx_mn4_type ON mn4_objects (object_type);+CREATE INDEX IF NOT EXISTS idx_mn4_doc ON mn4_objects (document_id);+CREATE INDEX IF NOT EXISTS idx_mn4_search ON mn4_objects (title);++CREATE TABLE IF NOT EXISTS mn4_devices (+ device_id TEXT PRIMARY KEY,+ device_name TEXT NOT NULL DEFAULT '',+ device_kind TEXT NOT NULL DEFAULT 'macos',+ token_hash TEXT NOT NULL,+ paired_at TEXT NOT NULL DEFAULT '',+ last_seen TEXT NOT NULL DEFAULT '',+ active INTEGER NOT NULL DEFAULT 1+);++CREATE TABLE IF NOT EXISTS mn4_cursors (+ device_id TEXT PRIMARY KEY,+ cursor TEXT NOT NULL DEFAULT ''+);++CREATE TABLE IF NOT EXISTS mn4_tombstones (+ object_id TEXT NOT NULL,+ device_id TEXT NOT NULL,+ deleted_at TEXT NOT NULL DEFAULT '',+ PRIMARY KEY (object_id, device_id)+);+"""+++def _now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _hash_token(token: str) -> str:+ return hashlib.sha256(token.encode()).hexdigest()+++def _default_db_path(kb_name: str) -> Path:+ """Default database location under DeepTutor's data directory."""+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in kb_name)+ from deeptutor.services.path_service import get_path_service++ return get_path_service().user_data_dir / "marginnote4" / f"{safe}.db"+++class MarginNoteStore:+ """CRUD + search over synced MN4 objects backed by SQLite.++ A single store instance serves one connected MarginNote 4 KB. The store+ owns its SQLite connection and is safe for sequential use from async code+ (each public method opens a short-lived connection).+ """++ def __init__(self, db_path: str | Path) -> None:+ self.db_path = Path(db_path)+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._init_schema()++ # -- internal helpers ---------------------------------------------------++ def _connect(self) -> sqlite3.Connection:+ conn = sqlite3.connect(str(self.db_path))+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA journal_mode=WAL")+ return conn++ def _init_schema(self) -> None:+ with self._connect() as conn:+ conn.executescript(_SCHEMA)++ @staticmethod+ def _row_to_object(row: sqlite3.Row) -> MarginNoteObject:+ return MarginNoteObject(+ object_id=row["object_id"],+ object_type=row["object_type"],+ title=row["title"],+ content=row["content"],+ excerpt=row["excerpt"],+ document_id=row["document_id"],+ document_title=row["document_title"],+ page=row["page"],+ tags=json.loads(row["tags"]),+ links=json.loads(row["links"]),+ color=row["color"],+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ synced_at=row["synced_at"],+ device_id=row["device_id"],+ raw=json.loads(row["raw"]),+ )++ # -- device pairing -----------------------------------------------------++ def pair_device(+ self,+ *,+ device_name: str = "",+ device_kind: str = "macos",+ ) -> tuple[PairedDevice, str]:+ """Register a new device. Returns ``(device, plaintext_token)``.++ The token is returned once; only its SHA-256 hash is stored. The+ caller must deliver it to the device over a trusted channel.+ """+ device_id = secrets.token_urlsafe(12)+ token = secrets.token_urlsafe(32)+ token_hash = _hash_token(token)+ now = _now_iso()+ device = PairedDevice(+ device_id=device_id,+ device_name=device_name,+ device_kind=device_kind,+ paired_at=now,+ last_seen=now,+ )+ with self._connect() as conn:+ conn.execute(+ """INSERT INTO mn4_devices+ (device_id, device_name, device_kind, token_hash,+ paired_at, last_seen, active)+ VALUES (?, ?, ?, ?, ?, ?, 1)""",+ (device_id, device_name, device_kind, token_hash, now, now),+ )+ conn.execute(+ "INSERT OR REPLACE INTO mn4_cursors (device_id, cursor) VALUES (?, '')",+ (device_id,),+ )+ return device, token++ def revoke_device(self, device_id: str) -> bool:+ """Mark a device inactive. Returns True if a row was affected."""+ with self._connect() as conn:+ cur = conn.execute(+ "UPDATE mn4_devices SET active = 0 WHERE device_id = ? AND active = 1",+ (device_id,),+ )+ return cur.rowcount > 0++ def verify_token(self, device_id: str, token: str) -> bool:+ """Check a device token against the stored hash."""+ with self._connect() as conn:+ row = conn.execute(+ "SELECT token_hash, active FROM mn4_devices WHERE device_id = ?",+ (device_id,),+ ).fetchone()+ if row is None or not row["active"]:+ return False+ return secrets.compare_digest(row["token_hash"], _hash_token(token))++ def list_devices(self) -> list[PairedDevice]:+ with self._connect() as conn:+ rows = conn.execute("SELECT * FROM mn4_devices ORDER BY paired_at").fetchall()+ return [_row_to_device(r) for r in rows]++ def touch_device(self, device_id: str) -> None:+ """Update last_seen timestamp for a device."""+ with self._connect() as conn:+ conn.execute(+ "UPDATE mn4_devices SET last_seen = ? WHERE device_id = ?",+ (_now_iso(), device_id),+ )++ # -- sync ingest --------------------------------------------------------++ def ingest(self, batch: SyncBatch) -> SyncResult:+ """Upsert a batch of objects and advance the device cursor."""+ stored = updated = deleted = 0+ now = _now_iso()+ with self._connect() as conn:+ for obj in batch.objects:+ if obj.object_type not in ALL_TYPES:+ logger.warning("Skipping unknown MN4 type: %s", obj.object_type)+ continue+ prev = conn.execute(+ "SELECT synced_at FROM mn4_objects WHERE object_id = ? AND device_id = ?",+ (obj.object_id, batch.device_id),+ ).fetchone()+ synced_at = obj.synced_at or now+ conn.execute(+ """INSERT INTO mn4_objects+ (object_id, device_id, object_type, title, content,+ excerpt, document_id, document_title, page, tags,+ links, color, created_at, updated_at, synced_at, raw)+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)+ ON CONFLICT(object_id, device_id) DO UPDATE SET+ object_type=excluded.object_type,+ title=excluded.title, content=excluded.content,+ excerpt=excluded.excerpt,+ document_id=excluded.document_id,+ document_title=excluded.document_title,+ page=excluded.page, tags=excluded.tags,+ links=excluded.links, color=excluded.color,+ created_at=excluded.created_at,+ updated_at=excluded.updated_at,+ synced_at=excluded.synced_at, raw=excluded.raw""",+ (+ obj.object_id,+ batch.device_id,+ obj.object_type,+ obj.title,+ obj.content,+ obj.excerpt,+ obj.document_id,+ obj.document_title,+ obj.page,+ json.dumps(obj.tags, ensure_ascii=False),+ json.dumps(obj.links, ensure_ascii=False),+ obj.color,+ obj.created_at,+ obj.updated_at,+ synced_at,+ json.dumps(obj.raw, ensure_ascii=False),+ ),+ )+ if prev:+ updated += 1+ else:+ stored += 1++ for oid in batch.deleted_ids:+ conn.execute(+ "INSERT OR REPLACE INTO mn4_tombstones "+ "(object_id, device_id, deleted_at) VALUES (?, ?, ?)",+ (oid, batch.device_id, now),+ )+ conn.execute(+ "DELETE FROM mn4_objects WHERE object_id = ? AND device_id = ?",+ (oid, batch.device_id),+ )+ deleted += 1++ new_cursor = _now_iso()+ conn.execute(+ "INSERT OR REPLACE INTO mn4_cursors (device_id, cursor) VALUES (?, ?)",+ (batch.device_id, new_cursor),+ )++ return SyncResult(stored=stored, updated=updated, deleted=deleted, new_cursor=new_cursor)++ def get_cursor(self, device_id: str) -> str:+ with self._connect() as conn:+ row = conn.execute(+ "SELECT cursor FROM mn4_cursors WHERE device_id = ?",+ (device_id,),+ ).fetchone()+ return row["cursor"] if row else ""++ # -- read operations ----------------------------------------------------++ def get(self, object_id: str, *, device_id: str = "") -> MarginNoteObject | None:+ """Fetch a single object by ID."""+ with self._connect() as conn:+ if device_id:+ row = conn.execute(+ "SELECT * FROM mn4_objects WHERE object_id = ? AND device_id = ?",+ (object_id, device_id),+ ).fetchone()+ else:+ row = conn.execute(+ "SELECT * FROM mn4_objects WHERE object_id = ? LIMIT 1",+ (object_id,),+ ).fetchone()+ return self._row_to_object(row) if row else None++ def search(+ self,+ query: str,+ *,+ object_type: str = "",+ device_id: str = "",+ limit: int = 20,+ ) -> list[dict[str, Any]]:+ """Case-insensitive substring search over titles and content."""+ query = (query or "").strip()+ if not query:+ return []+ needle = f"%{query.lower()}%"+ sql = (+ "SELECT * FROM mn4_objects "+ "WHERE (LOWER(title) LIKE ? OR LOWER(content) LIKE ? "+ "OR LOWER(COALESCE(excerpt, '')) LIKE ? "+ "OR LOWER(COALESCE(document_title, '')) LIKE ?)"+ )+ params: list[Any] = [needle, needle, needle, needle]+ if object_type:+ sql += " AND object_type = ?"+ params.append(object_type)+ if device_id:+ sql += " AND device_id = ?"+ params.append(device_id)+ sql += " ORDER BY updated_at DESC LIMIT ?"+ params.append(limit)+ with self._connect() as conn:+ rows = conn.execute(sql, params).fetchall()+ return [_to_summary(self._row_to_object(r), query) for r in rows]++ def list_objects(+ self,+ *,+ object_type: str = "",+ document_id: str = "",+ device_id: str = "",+ limit: int = 200,+ ) -> list[dict[str, Any]]:+ """List objects with optional type/document filter."""+ sql = "SELECT * FROM mn4_objects WHERE 1=1"+ params: list[Any] = []+ if object_type:+ sql += " AND object_type = ?"+ params.append(object_type)+ if document_id:+ sql += " AND document_id = ?"+ params.append(document_id)+ if device_id:+ sql += " AND device_id = ?"+ params.append(device_id)+ sql += " ORDER BY COALESCE(document_title, title), updated_at DESC LIMIT ?"+ params.append(limit)+ with self._connect() as conn:+ rows = conn.execute(sql, params).fetchall()+ return [_to_summary(self._row_to_object(r), "") for r in rows]++ def list_documents(self, *, device_id: str = "") -> list[dict[str, Any]]:+ """Distinct source documents with object counts."""+ sql = (+ "SELECT document_id, document_title, COUNT(*) AS n "+ "FROM mn4_objects WHERE document_id IS NOT NULL"+ )+ params: list[Any] = []+ if device_id:+ sql += " AND device_id = ?"+ params.append(device_id)+ sql += " GROUP BY document_id, document_title ORDER BY document_title"+ with self._connect() as conn:+ rows = conn.execute(sql, params).fetchall()+ return [+ {+ "document_id": r["document_id"],+ "title": r["document_title"] or "(untitled)",+ "count": int(r["n"]),+ }+ for r in rows+ ]++ def linked_objects(self, object_id: str, *, device_id: str = "") -> list[dict[str, Any]]:+ """Return objects linked TO or FROM the given object."""+ obj = self.get(object_id, device_id=device_id)+ if obj is None:+ return []+ linked_ids = set(obj.links)+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT object_id FROM mn4_objects WHERE links LIKE ?",+ (f'%"{object_id}"%',),+ ).fetchall()+ for r in rows:+ linked_ids.add(r["object_id"])+ results: list[dict[str, Any]] = []+ for lid in linked_ids:+ linked = self.get(lid, device_id=device_id)+ if linked:+ results.append(_to_summary(linked, ""))+ return results++ def collect_tags(self, *, device_id: str = "", limit: int = 200) -> list[dict[str, Any]]:+ """All tags across objects, ranked by frequency."""+ with self._connect() as conn:+ sql = "SELECT tags FROM mn4_objects"+ params: list[Any] = []+ if device_id:+ sql += " WHERE device_id = ?"+ params.append(device_id)+ rows = conn.execute(sql, params).fetchall()+ counts: dict[str, int] = {}+ for r in rows:+ for tag in json.loads(r["tags"]):+ tag = tag.strip()+ if tag:+ counts[tag] = counts.get(tag, 0) + 1+ ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))+ return [{"tag": t, "count": c} for t, c in ranked[:limit]]++ def count(self, *, device_id: str = "") -> int:+ """Total object count, optionally filtered by device."""+ with self._connect() as conn:+ if device_id:+ row = conn.execute(+ "SELECT COUNT(*) AS n FROM mn4_objects WHERE device_id = ?",+ (device_id,),+ ).fetchone()+ else:+ row = conn.execute("SELECT COUNT(*) AS n FROM mn4_objects").fetchone()+ return row["n"]+++def _row_to_device(row: sqlite3.Row) -> PairedDevice:+ return PairedDevice(+ device_id=row["device_id"],+ device_name=row["device_name"],+ device_kind=row["device_kind"],+ paired_at=row["paired_at"],+ last_seen=row["last_seen"],+ active=bool(row["active"]),+ )+++def _to_summary(obj: MarginNoteObject, query: str) -> dict[str, Any]:+ """Compact dict for search/list results (omits raw payload)."""+ body = obj.content or obj.excerpt or ""+ return {+ "object_id": obj.object_id,+ "object_type": obj.object_type,+ "title": obj.title,+ "document_title": obj.document_title,+ "page": obj.page,+ "tags": obj.tags,+ "snippet": _snippet(body, query),+ "updated_at": obj.updated_at,+ }+++def _snippet(body: str, query: str, width: int = 160) -> str:+ if not body:+ return ""+ if not query:+ return body[:width].strip().replace("\n", " ")+ lowered = body.lower()+ idx = lowered.find(query.lower())+ if idx < 0:+ return body[:width].strip().replace("\n", " ")+ start = max(0, idx - width // 3)+ tail = "..." if start + width < len(body) else ""+ return ("..." if start else "") + body[start : start + width].strip().replace("\n", " ") + tail+++__all__ = ["MarginNoteStore"]diff --git a/deeptutor/capabilities/marginnote4/tools.py b/deeptutor/capabilities/marginnote4/tools.pynew file mode 100644index 000000000..6ac0ab8cd--- /dev/null+++ b/deeptutor/capabilities/marginnote4/tools.py@@ -0,0 +1,329 @@+"""MarginNote 4 tools -- the seam between the chat loop and the synced store.++Seven tools auto-mounted only when a MarginNote 4 library is the selected KB+(via :class:`~deeptutor.capabilities.marginnote4.capability.MarginNoteCapability`,+which runs the turn exclusively on these tools). Five read the synced data+(search, read, list, links, tags) and two provide structural navigation+(documents, mindmap). Every tool is a thin wrapper over the pure+:class:`~deeptutor.capabilities.marginnote4.store.MarginNoteStore` methods.++The store path is injected server-side as ``_db_path`` by the capability's+``augment_kwargs``; the model never supplies or sees it.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++from deeptutor.capabilities.marginnote4.models import ALL_TYPES+from deeptutor.capabilities.marginnote4.store import MarginNoteStore+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult++MARGINNOTE_TOOL_NAMES: tuple[str, ...] = (+ "marginnote_search",+ "marginnote_read",+ "marginnote_list",+ "marginnote_documents",+ "marginnote_links",+ "marginnote_tags",+ "marginnote_cards",+)+++def _store(kwargs: dict[str, Any]) -> MarginNoteStore | None:+ raw = str(kwargs.get("_db_path") or "").strip()+ if not raw:+ return None+ root = Path(raw)+ cached = _STORE_CACHE.get(raw)+ if cached is not None:+ return cached+ if not root.parent.exists():+ return None+ store = MarginNoteStore(root)+ _STORE_CACHE[raw] = store+ return store+++_STORE_CACHE: dict[str, MarginNoteStore] = {}+++def _clear_store_cache() -> None:+ """Drop cached stores (tests that swap db files under the same path)."""+ _STORE_CACHE.clear()+++def _no_store_result() -> ToolResult:+ return ToolResult(+ content="No MarginNote 4 library is connected on this turn; "+ "MarginNote tools are unavailable.",+ success=False,+ )+++def _ok(payload: Any) -> ToolResult:+ return ToolResult(content=json.dumps(payload, ensure_ascii=False), success=True)+++def _err(message: str) -> ToolResult:+ return ToolResult(content=message, success=False)+++def _as_int(value: Any, *, default: int, lo: int, hi: int) -> int:+ try:+ out = int(value)+ except (TypeError, ValueError):+ return default+ return max(lo, min(hi, out))+++class _MN4Tool(BaseTool):+ """Shared store resolution + uniform error handling for MN4 tools."""++ async def execute(self, **kwargs: Any) -> ToolResult:+ store = _store(kwargs)+ if store is None:+ return _no_store_result()+ try:+ return await self._run(store, kwargs)+ except Exception as exc:+ return _err(str(exc))++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ raise NotImplementedError+++class MarginNoteSearchTool(_MN4Tool):+ """Full-text search across synced MN4 objects."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_search",+ description=(+ "Search the user's MarginNote 4 library for notes, excerpts, "+ "cards, or mindmap nodes whose title or content contains the "+ "query (case-insensitive). Returns matching objects with a "+ "short snippet. Use this first to find where something lives."+ ),+ parameters=[+ ToolParameter(+ name="query",+ type="string",+ description="Text to search for.",+ ),+ ToolParameter(+ name="object_type",+ type="string",+ description=(+ "Filter by type: note, excerpt, card, mindmap_node, document, comment."+ ),+ required=False,+ enum=sorted(ALL_TYPES),+ ),+ ToolParameter(+ name="limit",+ type="integer",+ description="Max results (default 20).",+ required=False,+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ query = str(kwargs.get("query") or "").strip()+ if not query:+ return _err("marginnote_search needs a non-empty 'query'.")+ obj_type = str(kwargs.get("object_type") or "").strip()+ limit = _as_int(kwargs.get("limit"), default=20, lo=1, hi=100)+ hits = store.search(query, object_type=obj_type, limit=limit)+ return _ok({"query": query, "count": len(hits), "results": hits})+++class MarginNoteReadTool(_MN4Tool):+ """Read a single MN4 object in full."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_read",+ description=(+ "Read a single MarginNote 4 object by its ID. Returns the full "+ "object: title, content, excerpt, tags, links, source document, "+ "and timestamps. Use after marginnote_search or "+ "marginnote_list to drill into a specific item."+ ),+ parameters=[+ ToolParameter(+ name="object_id",+ type="string",+ description="The MN4 object ID from a search or list result.",+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ oid = str(kwargs.get("object_id") or "").strip()+ if not oid:+ return _err("marginnote_read needs an 'object_id'.")+ obj = store.get(oid)+ if obj is None:+ return _err(f"Object {oid!r} not found in the MarginNote library.")+ return _ok(obj.to_dict())+++class MarginNoteListTool(_MN4Tool):+ """List objects, optionally filtered by type or source document."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_list",+ description=(+ "List MarginNote 4 objects, optionally filtered by type or "+ "source document. Use to discover structure when you lack a "+ "search term."+ ),+ parameters=[+ ToolParameter(+ name="object_type",+ type="string",+ description="Filter: note, excerpt, card, mindmap_node.",+ required=False,+ enum=sorted(ALL_TYPES),+ ),+ ToolParameter(+ name="document_id",+ type="string",+ description="Restrict to one source document.",+ required=False,+ ),+ ToolParameter(+ name="limit",+ type="integer",+ description="Max results (default 200).",+ required=False,+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ obj_type = str(kwargs.get("object_type") or "").strip()+ doc_id = str(kwargs.get("document_id") or "").strip()+ limit = _as_int(kwargs.get("limit"), default=200, lo=1, hi=1000)+ items = store.list_objects(object_type=obj_type, document_id=doc_id, limit=limit)+ return _ok({"count": len(items), "objects": items})+++class MarginNoteDocumentsTool(_MN4Tool):+ """List source documents with their object counts."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_documents",+ description=(+ "List all source documents (PDFs, books) in the MarginNote "+ "library with a count of annotations, cards, and nodes each "+ "contains. Use to scope a search to one document."+ ),+ parameters=[],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ docs = store.list_documents()+ return _ok({"count": len(docs), "documents": docs})+++class MarginNoteLinksTool(_MN4Tool):+ """Find objects linked to or from a given object."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_links",+ description=(+ "Find MarginNote objects linked TO or FROM the given object. "+ "Links include mindmap parent/child relationships and card "+ "links. Pair with marginnote_read to traverse the knowledge "+ "graph."+ ),+ parameters=[+ ToolParameter(+ name="object_id",+ type="string",+ description="The MN4 object ID to find links for.",+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ oid = str(kwargs.get("object_id") or "").strip()+ if not oid:+ return _err("marginnote_links needs an 'object_id'.")+ links = store.linked_objects(oid)+ return _ok({"object_id": oid, "count": len(links), "links": links})+++class MarginNoteTagsTool(_MN4Tool):+ """List all tags ranked by frequency."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_tags",+ description=(+ "List all tags used across the MarginNote library, ranked by "+ "how many objects use each. Use to map topics before drilling in."+ ),+ parameters=[+ ToolParameter(+ name="limit",+ type="integer",+ description="Max tags (default 200).",+ required=False,+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ limit = _as_int(kwargs.get("limit"), default=200, lo=1, hi=1000)+ tags = store.collect_tags(limit=limit)+ return _ok({"count": len(tags), "tags": tags})+++class MarginNoteCardsTool(_MN4Tool):+ """List flashcards for review-scope queries."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="marginnote_cards",+ description=(+ "List flashcards in the MarginNote library. Returns card "+ "front/back content, tags, and source document. Use when the "+ "user asks about their review material or wants to study."+ ),+ parameters=[+ ToolParameter(+ name="limit",+ type="integer",+ description="Max cards (default 100).",+ required=False,+ ),+ ],+ )++ async def _run(self, store: MarginNoteStore, kwargs: dict[str, Any]) -> ToolResult:+ limit = _as_int(kwargs.get("limit"), default=100, lo=1, hi=500)+ cards = store.list_objects(object_type="card", limit=limit)+ return _ok({"count": len(cards), "cards": cards})+++MARGINNOTE_TOOL_TYPES: tuple[type[BaseTool], ...] = (+ MarginNoteSearchTool,+ MarginNoteReadTool,+ MarginNoteListTool,+ MarginNoteDocumentsTool,+ MarginNoteLinksTool,+ MarginNoteTagsTool,+ MarginNoteCardsTool,+)+++__all__ = ["MARGINNOTE_TOOL_NAMES", "MARGINNOTE_TOOL_TYPES"]diff --git a/deeptutor/capabilities/registry.py b/deeptutor/capabilities/registry.pyindex 73abf4e40..ed1705c44 100644--- a/deeptutor/capabilities/registry.py+++ b/deeptutor/capabilities/registry.py@@ -9,6 +9,7 @@ from typing import Anyfrom deeptutor.capabilities.explore_context import ExploreContextCapabilityfrom deeptutor.capabilities.ima import ImaCapability+from deeptutor.capabilities.marginnote4 import MarginNoteCapabilityfrom deeptutor.capabilities.mastery import MasteryLoopCapabilityfrom deeptutor.capabilities.obsidian import ObsidianCapabilityfrom deeptutor.capabilities.protocol import LoopCapability@@ -27,6 +28,7 @@ LOOP_CAPABILITIES: tuple[LoopCapability, ...] = (MasteryLoopCapability(),SolveLoopCapability(),ObsidianCapability(),+ MarginNoteCapability(),SubagentCapability(),# Additive (not a KnowledgeCapability): an IMA library is searchable over# HTTP, so ``rag`` keeps serving it and these tools only add what retrievaldiff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.pyindex 90247178e..f1ff2a3a4 100644--- a/deeptutor/knowledge/kb_types.py+++ b/deeptutor/knowledge/kb_types.py@@ -74,6 +74,13 @@ LIGHTRAG_SERVER_KB_TYPE = "lightrag_server"# ``search_knowledge`` OpenAPI by the ``ima`` provider.IMA_KB_TYPE = "ima"+# A connected MarginNote 4 library: a pointer (``device_id`` + optional+# ``server_url``) to the user's MN4 study data synced via the official Add-on+# API. No path on disk and no local index — MN4 objects land in a dedicated+# SQLite store and are navigated by the MarginNote capability's own tools.+# See ``capabilities/marginnote4``.+MARGINNOTE4_KB_TYPE = "marginnote4"+# Every pointer/connected KB type. Membership here is what makes the manager# skip the index pipeline, the orphan prune and the embedding reconcile.CONNECTED_KB_TYPES = frozenset(@@ -83,6 +90,7 @@ CONNECTED_KB_TYPES = frozenset(SUBAGENT_KB_TYPE,LIGHTRAG_SERVER_KB_TYPE,IMA_KB_TYPE,+ MARGINNOTE4_KB_TYPE,})@@ -93,7 +101,7 @@ CONNECTED_KB_TYPES = frozenset(# mounts an index built elsewhere, while ``lightrag_server`` and ``ima`` offload# retrieval over HTTP — so "connected" must never be used as a synonym for# "unsearchable" (it once cost Book generation every one of those sources).-NON_RETRIEVABLE_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, SUBAGENT_KB_TYPE})+NON_RETRIEVABLE_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, SUBAGENT_KB_TYPE, MARGINNOTE4_KB_TYPE})def is_connected_kb(entry: Any) -> bool:@@ -141,6 +149,7 @@ __all__ = ["SUBAGENT_KB_TYPE","LIGHTRAG_SERVER_KB_TYPE","IMA_KB_TYPE",+ "MARGINNOTE4_KB_TYPE","CONNECTED_KB_TYPES","NON_RETRIEVABLE_KB_TYPES","is_connected_kb",diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex a5ef68346..55f2087c9 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -21,6 +21,7 @@ from deeptutor.knowledge.kb_types import (IMA_KB_TYPE,LIGHTRAG_SERVER_KB_TYPE,LINKED_KB_TYPE,+ MARGINNOTE4_KB_TYPE,OBSIDIAN_KB_TYPE,SUBAGENT_KB_TYPE,external_root_of,@@ -892,6 +893,48 @@ class KnowledgeBaseManager:self._save_config()return entry+ def register_marginnote4_kb(+ self,+ name: str,+ *,+ db_path: str = "",+ description: str = "",+ ) -> dict:+ """Register a connected MarginNote 4 library as a pointer KB.++ Creates no folder under ``base_dir`` and runs no index pipeline: it+ records a ``type: marginnote4`` entry whose ``db_path`` (when given)+ 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.+ """+ name = (name or "").strip()+ if not name:+ raise ValueError("Knowledge base name is required.")++ self.config = self._load_config()+ knowledge_bases = self.config.setdefault("knowledge_bases", {})+ if name in knowledge_bases:+ raise ValueError(f"A knowledge base named '{name}' already exists.")++ now = datetime.now().isoformat()+ entry: dict[str, Any] = {+ "path": name,+ "type": MARGINNOTE4_KB_TYPE,+ "description": description or f"MarginNote 4 library: {name}",+ "status": "ready",+ "needs_reindex": False,+ "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+def register_ima_kb(self,name: str,@@ -1099,6 +1142,8 @@ class KnowledgeBaseManager:"type": kb_config.get("type"),"vault_path": kb_config.get("vault_path"),"external_path": kb_config.get("external_path"),+ # MarginNote 4 pointer (SQLite store path for synced data).+ "db_path": kb_config.get("db_path"),# LightRAG server pointer (the URL is safe to surface; the API# key deliberately is not)."server_url": kb_config.get("server_url"),@@ -1253,6 +1298,8 @@ class KnowledgeBaseManager:metadata["vault_path"] = kb_config.get("vault_path")if kb_config.get("external_path"):metadata["external_path"] = kb_config.get("external_path")+ if kb_config.get("db_path"):+ metadata["db_path"] = kb_config.get("db_path")if kb_config.get("agent_kind"):metadata["agent_kind"] = kb_config.get("agent_kind")# The server URL is shown read-only in the UI; the API key never leavesdiff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex b6c447ca3..e2e485f04 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -8,6 +8,7 @@ import loggingfrom typing import Anyfrom deeptutor.capabilities.ima import IMA_TOOL_TYPES+from deeptutor.capabilities.marginnote4 import MARGINNOTE_TOOL_TYPESfrom deeptutor.capabilities.mastery import MASTERY_TOOL_TYPESfrom deeptutor.capabilities.obsidian import OBSIDIAN_TOOL_TYPESfrom deeptutor.capabilities.reading import READING_TOOL_TYPES@@ -1713,6 +1714,7 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (*MASTERY_TOOL_TYPES,*SOLVE_TOOL_TYPES,*OBSIDIAN_TOOL_TYPES,+ *MARGINNOTE_TOOL_TYPES,# Subagent consult tool — globally registered; the subagent knowledge# capability runs the turn exclusively on it when a connected agent is the# selected KB.diff --git a/tests/capabilities/marginnote4/__init__.py b/tests/capabilities/marginnote4/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/capabilities/marginnote4/test_capability.py b/tests/capabilities/marginnote4/test_capability.pynew file mode 100644index 000000000..61c040b69--- /dev/null+++ b/tests/capabilities/marginnote4/test_capability.py@@ -0,0 +1,106 @@+"""Tests for the MarginNote 4 capability: binding, hooks, exclusivity."""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.capabilities import any_exclusive_capability_active+from deeptutor.capabilities.marginnote4 import (+ MARGINNOTE_TOOL_NAMES,+ MarginNoteCapability,+)+from deeptutor.capabilities.marginnote4 import binding as mn4_binding+from deeptutor.core.context import UnifiedContext+++def _bind(monkeypatch, db_path: str, name: str = "mylibrary") -> None:+ """Make resolve_kb_metadata report ``name`` as a marginnote4 KB."""+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda ref: (+ {"name": ref, "type": "marginnote4", "db_path": db_path}+ if ref == name+ else {"name": ref, "type": None}+ ),+ )+++def test_capability_inactive_without_mn4_kb(monkeypatch, tmp_path: Path) -> None:+ _bind(monkeypatch, str(tmp_path / "test.db"))+ cap = MarginNoteCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["plain-kb"])+ assert cap.is_active(ctx) is False+ assert cap.system_block(ctx, language="en", prompts={}) is None+++def test_capability_active_injects_db_path(monkeypatch, tmp_path: Path) -> None:+ db_path = str(tmp_path / "test.db")+ _bind(monkeypatch, db_path)+ cap = MarginNoteCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["mylibrary"])+ assert cap.is_active(ctx) is True+ assert tuple(cap.owned_tools) == MARGINNOTE_TOOL_NAMES+ # db_path injected for marginnote tools, even overwriting a forged value+ assert cap.augment_kwargs("marginnote_read", {}, ctx)["_db_path"] == db_path+ assert cap.augment_kwargs("marginnote_read", {"_db_path": "/etc"}, ctx)["_db_path"] == db_path+ # but never for a non-marginnote tool+ assert "_db_path" not in cap.augment_kwargs("rag", {}, ctx)+++def test_system_block_contains_library_name(monkeypatch, tmp_path: Path) -> None:+ _bind(monkeypatch, str(tmp_path / "test.db"))+ cap = MarginNoteCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["mylibrary"])+ block = cap.system_block(ctx, language="en", prompts={})+ assert block is not None+ assert "mylibrary" in block.content+++def test_system_block_zh(monkeypatch, tmp_path: Path) -> None:+ _bind(monkeypatch, str(tmp_path / "test.db"))+ cap = MarginNoteCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["mylibrary"])+ block = cap.system_block(ctx, language="zh", prompts={})+ assert block is not None+++def test_binding_resolved_once_and_cached(monkeypatch, tmp_path: Path) -> None:+ calls = {"n": 0}++ def fake(ref):+ calls["n"] += 1+ return {"name": ref, "type": "marginnote4", "db_path": str(tmp_path / "x.db")}++ monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", fake)+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["lib"])+ mn4_binding.marginnote_binding(ctx)+ mn4_binding.marginnote_binding(ctx)+ assert calls["n"] == 1 # cached after first resolution+++def test_owned_kbs_reports_only_mn4_refs(monkeypatch, tmp_path: Path) -> None:+ _bind(monkeypatch, str(tmp_path / "test.db"))+ cap = MarginNoteCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["mylibrary", "kb-plain"])+ assert cap.owned_kbs(ctx) == {"mylibrary"}+++def test_kb_refs_enumerates_every_selected_library(monkeypatch, tmp_path: Path) -> None:+ def fake(ref):+ if ref in {"libA", "libB"}:+ return {"name": ref, "type": "marginnote4", "db_path": str(tmp_path / "x.db")}+ return {"name": ref, "type": None}++ monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", fake)+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["libA", "kb1", "libB"])+ assert mn4_binding.marginnote_kb_refs(ctx) == {"libA", "libB"}+++def test_exclusive_flag_replaces_tool_surface(monkeypatch, tmp_path: Path) -> None:+ _bind(monkeypatch, str(tmp_path / "test.db"))+ mn4_turn = UnifiedContext(user_message="hi", knowledge_bases=["mylibrary"])+ plain_turn = UnifiedContext(user_message="hi", knowledge_bases=["plain-kb"])+ assert any_exclusive_capability_active(mn4_turn) is True+ assert any_exclusive_capability_active(plain_turn) is Falsediff --git a/tests/capabilities/marginnote4/test_store.py b/tests/capabilities/marginnote4/test_store.pynew file mode 100644index 000000000..2fa7808b4--- /dev/null+++ b/tests/capabilities/marginnote4/test_store.py@@ -0,0 +1,241 @@+"""Tests for the MarginNote 4 SQLite store: pairing, sync ingest, search."""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.capabilities.marginnote4.models import (+ CARD,+ DOCUMENT,+ MINDMAP_NODE,+ NOTE,+ MarginNoteObject,+ SyncBatch,+)+from deeptutor.capabilities.marginnote4.store import MarginNoteStore+++def _seed_objects(device_id: str = "dev1") -> list[MarginNoteObject]:+ return [+ MarginNoteObject(+ object_id="note1",+ object_type=NOTE,+ title="Photosynthesis",+ content="Plants convert light into chemical energy.",+ excerpt="The process by which green plants use sunlight...",+ document_id="doc1",+ document_title="Biology Textbook",+ page=42,+ tags=["biology", "plants"],+ links=["card1"],+ color="yellow",+ created_at="2025-01-01T00:00:00Z",+ updated_at="2025-01-02T00:00:00Z",+ device_id=device_id,+ ),+ MarginNoteObject(+ object_id="card1",+ object_type=CARD,+ title="What is photosynthesis?",+ content="Process of converting light energy to chemical energy",+ tags=["biology"],+ links=["note1"],+ device_id=device_id,+ ),+ MarginNoteObject(+ object_id="node1",+ object_type=MINDMAP_NODE,+ title="Energy Conversion",+ content="Central concept linking photosynthesis and respiration",+ links=["note1", "card1"],+ device_id=device_id,+ ),+ ]+++# ---- device pairing --------------------------------------------------------+++def test_pair_device_returns_token(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ device, token = store.pair_device(device_name="MacBook", device_kind="macos")+ assert device.device_id+ assert len(token) > 20+ assert device.device_name == "MacBook"+ assert device.device_kind == "macos"+++def test_verify_token_roundtrip(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ device, token = store.pair_device(device_name="iPad")+ assert store.verify_token(device.device_id, token) is True+ assert store.verify_token(device.device_id, "wrong") is False+ assert store.verify_token("nonexistent", token) is False+++def test_revoke_device_blocks_token(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ device, token = store.pair_device()+ assert store.verify_token(device.device_id, token) is True+ assert store.revoke_device(device.device_id) is True+ assert store.verify_token(device.device_id, token) is False+ assert store.revoke_device(device.device_id) is False # already revoked+++# ---- sync ingest -----------------------------------------------------------+++def test_ingest_stores_objects(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ objects = _seed_objects()+ batch = SyncBatch(device_id="dev1", objects=objects)+ result = store.ingest(batch)+ assert result.stored == 3+ assert result.updated == 0+ assert result.deleted == 0+ assert result.new_cursor+ assert store.count(device_id="dev1") == 3+++def test_ingest_updates_existing(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ objects = _seed_objects()+ store.ingest(SyncBatch(device_id="dev1", objects=objects))+ # Re-sync with updated content+ updated = [+ MarginNoteObject(+ object_id="note1",+ object_type=NOTE,+ title="Photosynthesis Updated",+ content="New content",+ device_id="dev1",+ )+ ]+ result = store.ingest(SyncBatch(device_id="dev1", objects=updated))+ assert result.stored == 0+ assert result.updated == 1+ obj = store.get("note1")+ assert obj is not None+ assert obj.title == "Photosynthesis Updated"+++def test_ingest_handles_deletions(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ result = store.ingest(SyncBatch(device_id="dev1", deleted_ids=["note1", "card1"]))+ assert result.deleted == 2+ assert store.count(device_id="dev1") == 1+ assert store.get("note1") is None+++def test_ingest_skips_unknown_types(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ bad = [MarginNoteObject(object_id="bad1", object_type="unknown_type", device_id="dev1")]+ result = store.ingest(SyncBatch(device_id="dev1", objects=bad))+ assert result.stored == 0+ assert store.count() == 0+++# ---- search ----------------------------------------------------------------+++def test_search_finds_by_unique_term(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ # "chlorophyll" appears only in note1+ hits = store.search("chlorophyll")+ # Adjust: search for a term unique to one object+ hits = store.search("green plants")+ assert len(hits) == 1+ assert hits[0]["object_id"] == "note1"+++def test_search_finds_common_term_across_objects(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ # "photosynthesis" appears in note1 title, card1 title, and node1 content+ hits = store.search("photosynthesis")+ assert len(hits) == 3+ ids = {h["object_id"] for h in hits}+ assert "note1" in ids+ assert "card1" in ids+ assert "node1" in ids+++def test_search_includes_document_title(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ # "Biology Textbook" is a document_title, not in any note's content+ hits = store.search("Biology Textbook")+ assert len(hits) >= 1+ assert any(h["object_id"] == "note1" for h in hits)+++def test_search_filters_by_type(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ hits = store.search("energy", object_type="card")+ assert len(hits) == 1+ assert hits[0]["object_type"] == "card"+++def test_search_empty_query_returns_nothing(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ assert store.search("") == []+++# ---- list / documents / tags ----------------------------------------------+++def test_list_objects_by_type(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ cards = store.list_objects(object_type="card")+ assert len(cards) == 1+ assert cards[0]["object_id"] == "card1"+++def test_list_documents_grouped(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ docs = store.list_documents()+ assert len(docs) == 1+ assert docs[0]["document_id"] == "doc1"+ assert docs[0]["title"] == "Biology Textbook"+ assert int(docs[0]["count"]) == 1+++def test_collect_tags_ranked(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ tags = store.collect_tags()+ tag_map = {t["tag"]: t["count"] for t in tags}+ assert tag_map["biology"] == 2 # note1 + card1+ assert tag_map["plants"] == 1+++# ---- links -----------------------------------------------------------------+++def test_linked_objects_bidirectional(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ links = store.linked_objects("note1")+ linked_ids = {item["object_id"] for item in links}+ assert "card1" in linked_ids # note1.links includes card1+ assert "node1" in linked_ids # node1.links includes note1+++# ---- cursor ----------------------------------------------------------------+++def test_cursor_advances(tmp_path: Path) -> None:+ store = MarginNoteStore(tmp_path / "test.db")+ assert store.get_cursor("dev1") == ""+ result = store.ingest(SyncBatch(device_id="dev1", objects=_seed_objects()))+ cursor = store.get_cursor("dev1")+ assert cursor != ""+ assert cursor == result.new_cursordiff --git a/tests/capabilities/marginnote4/test_tools.py b/tests/capabilities/marginnote4/test_tools.pynew file mode 100644index 000000000..411fbdd13--- /dev/null+++ b/tests/capabilities/marginnote4/test_tools.py@@ -0,0 +1,173 @@+"""Tests for the MarginNote 4 tools against an in-memory store."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from deeptutor.capabilities.marginnote4.models import (+ CARD,+ NOTE,+ MarginNoteObject,+ SyncBatch,+)+from deeptutor.capabilities.marginnote4.store import MarginNoteStore+from deeptutor.capabilities.marginnote4.tools import (+ MarginNoteCardsTool,+ MarginNoteDocumentsTool,+ MarginNoteLinksTool,+ MarginNoteListTool,+ MarginNoteReadTool,+ MarginNoteSearchTool,+ MarginNoteTagsTool,+ _clear_store_cache,+)+++def _seed_store(tmp_path: Path) -> str:+ """Seed a store with test data and return its db_path for tool calls."""+ _clear_store_cache()+ store = MarginNoteStore(tmp_path / "test.db")+ store.ingest(+ SyncBatch(+ device_id="dev1",+ objects=[+ MarginNoteObject(+ object_id="note1",+ object_type=NOTE,+ title="Photosynthesis",+ content="Plants convert light into chemical energy.",+ excerpt="The process by which green plants use sunlight...",+ document_id="doc1",+ document_title="Biology Textbook",+ page=42,+ tags=["biology"],+ links=["card1"],+ device_id="dev1",+ ),+ MarginNoteObject(+ object_id="card1",+ object_type=CARD,+ title="What is photosynthesis?",+ content="Process of converting light to chemical energy",+ tags=["biology"],+ links=["note1"],+ device_id="dev1",+ ),+ ],+ )+ )+ return str(tmp_path / "test.db")+++async def test_search_finds_results(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ # "green plants" appears only in note1's excerpt+ res = await MarginNoteSearchTool().execute(query="green plants", _db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["count"] == 1+ assert data["results"][0]["object_id"] == "note1"+++async def test_search_finds_common_term(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ # "photosynthesis" appears in both note1 and card1 titles+ res = await MarginNoteSearchTool().execute(query="photosynthesis", _db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["count"] >= 1+++async def test_search_empty_query_fails(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteSearchTool().execute(query="", _db_path=db_path)+ assert res.success is False+++async def test_read_returns_full_object(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteReadTool().execute(object_id="note1", _db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["title"] == "Photosynthesis"+ assert data["document_title"] == "Biology Textbook"+ assert data["page"] == 42+ assert data["tags"] == ["biology"]+++async def test_read_missing_object_fails(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteReadTool().execute(object_id="nonexistent", _db_path=db_path)+ assert res.success is False+++async def test_list_by_type(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteListTool().execute(object_type="card", _db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["count"] == 1+ assert data["objects"][0]["object_id"] == "card1"+++async def test_documents_lists_sources(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteDocumentsTool().execute(_db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["count"] == 1+ assert data["documents"][0]["title"] == "Biology Textbook"+++async def test_links_finds_connections(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteLinksTool().execute(object_id="note1", _db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ linked_ids = {item["object_id"] for item in data["links"]}+ assert "card1" in linked_ids+++async def test_tags_returns_ranked(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteTagsTool().execute(_db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert any(t["tag"] == "biology" for t in data["tags"])+++async def test_cards_lists_flashcards(tmp_path: Path) -> None:+ db_path = _seed_store(tmp_path)+ res = await MarginNoteCardsTool().execute(_db_path=db_path)+ assert res.success+ data = json.loads(res.content)+ assert data["count"] == 1+ assert data["cards"][0]["object_type"] == "card"+++async def test_tools_fail_without_store() -> None:+ res = await MarginNoteSearchTool().execute(query="test")+ assert res.success is False+ assert "MarginNote" in res.content+++async def test_tools_fail_with_nonexistent_path(tmp_path: Path) -> None:+ res = await MarginNoteSearchTool().execute(+ query="test", _db_path=str(tmp_path / "nonexistent" / "missing.db")+ )+ assert res.success is Falsediff --git a/tests/knowledge/test_marginnote4_kb.py b/tests/knowledge/test_marginnote4_kb.pynew file mode 100644index 000000000..418fc8cb2--- /dev/null+++ b/tests/knowledge/test_marginnote4_kb.py@@ -0,0 +1,111 @@+"""Manager handling of connected MarginNote 4 KBs (``type: marginnote4`` pointers).++A connected MN4 library is a pointer with no on-disk KB folder and no index,+so the manager must (1) not prune it as an orphan, (2) not run provider/embedding+normalization on it, and (3) surface its ``type`` through ``get_metadata`` so the+capability layer can bind to it.+"""++from __future__ import annotations++import json+from pathlib import Path++from deeptutor.knowledge.manager import KnowledgeBaseManager+++def _seed_mn4(manager: KnowledgeBaseManager, name: str, db_path: str = "") -> None:+ entry: dict = {"type": "marginnote4", "description": "Connected MN4 library"}+ if db_path:+ entry["db_path"] = db_path+ manager.config.setdefault("knowledge_bases", {})[name] = entry+ manager._save_config()+++def test_mn4_entry_survives_orphan_prune(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ _seed_mn4(manager, "MyLibrary")+ assert "MyLibrary" in manager.list_knowledge_bases()+ persisted = json.loads(manager.config_file.read_text(encoding="utf-8"))+ assert "MyLibrary" in persisted.get("knowledge_bases", {})+++def test_get_metadata_surfaces_type(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ _seed_mn4(manager, "MyLibrary", db_path="/data/mn4/test.db")+ meta = manager.get_metadata("MyLibrary")+ assert meta["type"] == "marginnote4"+ assert meta["db_path"] == "/data/mn4/test.db"+++def test_reconcile_does_not_clobber_mn4_entry(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ _seed_mn4(manager, "MyLibrary", db_path="/data/mn4/test.db")+ reloaded = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ entry = reloaded.config["knowledge_bases"]["MyLibrary"]+ assert entry["type"] == "marginnote4"+ assert entry["db_path"] == "/data/mn4/test.db"+ assert entry.get("needs_reindex") is not True+ assert "index_versions" not in entry+++def test_ordinary_kb_metadata_has_no_mn4_fields(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ kb_dir = manager.base_dir / "plain"+ (kb_dir / "version-1").mkdir(parents=True)+ (kb_dir / "version-1" / "docstore.json").write_text("{}", encoding="utf-8")+ manager.config.setdefault("knowledge_bases", {})["plain"] = {"path": "plain", "status": "ready"}+ manager._save_config()+ meta = manager.get_metadata("plain")+ assert "type" not in meta+ assert "db_path" not in meta+++def test_register_marginnote4_kb_creates_pointer(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ entry = manager.register_marginnote4_kb(+ "MyLibrary", db_path="/data/mn4/test.db", description="Test lib"+ )+ assert entry["type"] == "marginnote4"+ assert entry["db_path"] == "/data/mn4/test.db"+ assert entry["description"] == "Test lib"+ assert "MyLibrary" in manager.list_knowledge_bases()+++def test_register_marginnote4_kb_default_path(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ entry = manager.register_marginnote4_kb("AutoPath")+ assert entry["type"] == "marginnote4"+ assert "db_path" not in entry # capability derives default from name+++def test_register_marginnote4_kb_rejects_duplicate(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ manager.register_marginnote4_kb("Lib")+ import pytest++ with pytest.raises(ValueError, match="already exists"):+ manager.register_marginnote4_kb("Lib")+++def test_mn4_is_connected_but_not_rag_retrievable() -> None:+ """MN4 objects live in their own store, so ``rag_search`` cannot reach them.++ Membership in ``CONNECTED_KB_TYPES`` alone would leave+ ``supports_rag_retrieval`` true and let Book sweep the library, which+ returns nothing and reads as "your MN4 notes had no relevant content"+ instead of "this source needs its own tools".+ """+ from deeptutor.knowledge.kb_types import is_connected_kb, supports_rag_retrieval++ entry = {"type": "marginnote4", "db_path": "/data/mn4/test.db"}+ assert is_connected_kb(entry) is True+ assert supports_rag_retrieval(entry) is False+++def test_connected_kbs_backed_by_an_index_stay_retrievable() -> None:+ """Guard the distinction: "connected" is not the same as "unsearchable"."""+ from deeptutor.knowledge.kb_types import supports_rag_retrieval++ for kb_type in ("linked", "lightrag_server", "ima"):+ assert supports_rag_retrieval({"type": kb_type}) is True