Files
evan188199-tech 1413cd8ed0 feat(knowledge): add MarginNote 4 as a connected knowledge base (#931)
* feat(marginnote4): add connected KB type, read-only tools, and sync bridge

Add MarginNote 4 as a connected knowledge base type that syncs study data
(notes, excerpts, cards, mindmap nodes) from MN4 via the official Add-on API
into a dedicated SQLite store, then exposes it to the chat loop through seven
read-only tools.

New package: deeptutor/capabilities/marginnote4/
- models.py: MarginNoteObject, SyncBatch, PairedDevice, LearningEvent
- store.py: SQLite CRUD + search + device pairing with hashed tokens
- binding.py: per-turn resolution of the selected MN4 library
- tools.py: search, read, list, documents, links, tags, cards
- capability.py: KnowledgeCapability (exclusive turn ownership)
- prompts/{en,zh}/system.md

HTTP bridge: deeptutor/api/routers/marginnote4.py
- POST /pair (session auth) -- register a device, get one-time token
- POST /sync (device-token auth) -- incremental upsert + tombstones
- POST /heartbeat (device-token auth) -- liveness + object count
- GET /devices, DELETE /devices/{id}, GET /status (session auth)

Integration points:
- kb_types.py: MARGINNOTE4_KB_TYPE added to CONNECTED_KB_TYPES
- manager.py: db_path surfaced in get_metadata allowlist
- registry.py: MarginNoteCapability registered in LOOP_CAPABILITIES
- builtin/__init__.py: MARGINNOTE_TOOL_TYPES in BUILTIN_TOOL_TYPES
- api/main.py: router mounted at /api/v1/marginnote4

Phase 1 scope: device pairing, read-only sync, tool navigation.
Write-back (propose/apply/verify), learning events, and mastery bridge
are planned for Phase 2-3.

Refs: #756 (Obsidian external knowledge source pattern), #180

* fix(marginnote4): search scope, store caching, prompts, KB registration

Testing and experience improvements:

- Search now includes document_title in scope: searching for a textbook
  name returns results instead of zero hits
- Store instances cached by db_path so schema init runs once, not per
  tool call within a turn
- object_type parameters carry enum constraints so the LLM knows valid
  types without guessing
- System prompts (en/zh) rewritten with domain context: explains the
  five object types, link traversal strategy, and citation guidance
- KB registration: register_marginnote4_kb manager method +
  /connect-marginnote4 API endpoint, mirroring the Obsidian connect flow
- Fix indentation inconsistencies in manager.py and main.py
- New tests: document_title search scope, KB registration (create,
  default path, duplicate rejection)

65 tests pass, 0 regressions, ruff clean.

* style(marginnote4): apply repository formatter

* fix(marginnote4): keep MN4 libraries out of the rag_search sweep

``MARGINNOTE4_KB_TYPE`` joined ``CONNECTED_KB_TYPES`` but not
``NON_RETRIEVABLE_KB_TYPES``, so ``supports_rag_retrieval`` answered true
for a library that has no index and no retrieval API — its objects live
in ``mn4_objects`` and are reachable only through the seven
``marginnote_*`` tools. Book's source explorer would have swept it,
gotten nothing back, and reported it as a source with no relevant
content rather than one that needs its own tools.

MN4 belongs with ``obsidian`` and ``subagent``, not with ``linked`` /
``lightrag_server`` / ``ima``, which do resolve to an index or an HTTP
retrieval API. Tests pin both halves of that split, since collapsing it
the other way has cost Book its connected sources before.

---------

Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: evan <evan@dazongguandeMac-mini.local>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-21 16:10:22 +08:00

174 lines
5.6 KiB
Python

"""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")
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"]
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"])
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
async def test_tools_fail_without_store() -> None:
res = await MarginNoteSearchTool().execute(query="test")
assert res.success is False
assert "MarginNote" in res.content
@pytest.mark.asyncio
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 False