DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(learner): add account-scoped reading learning records (#1109)
XZHfacbc020b97a
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex b49c68cc9..f90498a53 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -23,6 +23,7 @@ from deeptutor.learning.models import (LearningProgress,MasteryInteraction,MasteryTopic,+ ReadingLearningRecords,TopicMetadata,TopicSource,TopicSourceKind,@@ -363,6 +364,14 @@ async def list_topic_index():}[email protected]("/reading/records", response_model=ReadingLearningRecords)+async def list_reading_learning_records() -> ReadingLearningRecords:+ """Reading progress and extension activity for the current account."""++ store = LearningStore()+ return await asyncio.to_thread(store.list_reading_records)++@router.post("/topics/draft")async def generate_topic_route(body: GenerateTopicDraftRequest):from deeptutor.learning.topic_generation import TopicGenerationError, generate_topic_draftdiff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.pyindex f09176edd..f19abfff3 100644--- a/deeptutor/api/routers/reading.py+++ b/deeptutor/api/routers/reading.py@@ -29,6 +29,7 @@ from fastapi.params import Filefrom fastapi.responses import FileResponse, Responsefrom pydantic import BaseModel, Field, model_validator+from deeptutor.learning.storage import LearningStorefrom deeptutor.multi_user.learning_access import (assert_learning_material,assert_learning_material_mutation,@@ -88,6 +89,14 @@ def _store() -> ReadingStore:return ReadingStore()+def _record_reading_position(material_id: str, *, locator: int, percentage: float) -> None:+ LearningStore().record_reading_position(+ material_id,+ locator=locator,+ percentage=percentage,+ )++def _catalog() -> ReadingCatalogStore:return ReadingCatalogStore()@@ -1253,6 +1262,12 @@ async def save_position(material_id: str, payload: PositionPayload) -> PositionIpercentage=payload.percentage,),)+ await asyncio.to_thread(+ _record_reading_position,+ material_id,+ locator=saved.locator,+ percentage=saved.percentage,+ )return PositionInfo(**saved.to_dict())except Exception as exc:raise _http_error(exc) from excdiff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.pyindex e4559f975..a1a6e510d 100644--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@ -10,6 +10,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field, ValidationError+from deeptutor.learning.storage import LearningStorefrom deeptutor.multi_user.learning_access import (allowed_reading_extensions,assert_learning_material,@@ -40,6 +41,23 @@ def _verified_selection(candidate: str, unit_text: str) -> str:return value if value and value in _normal(unit_text) else ""+def _record_reading_activity(+ material_id: str,+ *,+ extension_id: str,+ action: str,+ locator: int,+ result_type: str,+) -> None:+ LearningStore().record_reading_activity(+ material_id,+ extension_id=extension_id,+ action=action,+ locator=locator,+ result_type=result_type,+ )++@router.get("/extensions")async def list_extensions() -> list[dict[str, Any]]:allowed = allowed_reading_extensions()@@ -122,7 +140,6 @@ async def run_extension_action()if result.type not in extension.manifest.result_types:raise ValueError(f"Extension returned undeclared result type {result.type!r}.")- return result.model_dump()except TimeoutError as exc:registry.mark_timed_out(extension_id)raise HTTPException(@@ -143,5 +160,15 @@ async def run_extension_action(finally:registry.finish_action(extension_id)+ await asyncio.to_thread(+ _record_reading_activity,+ material_id,+ extension_id=extension_id,+ action=action,+ locator=payload.locator,+ result_type=result.type,+ )+ return result.model_dump()+__all__ = ["router"]diff --git a/deeptutor/learning/__init__.py b/deeptutor/learning/__init__.pyindex fabf2adb8..7fd154128 100644--- a/deeptutor/learning/__init__.py+++ b/deeptutor/learning/__init__.py@@ -25,6 +25,9 @@ from deeptutor.learning.models import (MasteryPathLease,PendingQuestion,QuizAttempt,+ ReadingActivityRecord,+ ReadingLearningRecords,+ ReadingProgressRecord,RepetitionState,RetryAttempt,ReviewTask,@@ -44,6 +47,9 @@ __all__ = ["MasteryInteraction","MasteryPathLease","PendingQuestion",+ "ReadingActivityRecord",+ "ReadingLearningRecords",+ "ReadingProgressRecord","QuizAttempt","RepetitionState","RetryAttempt",diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.pyindex 3f7d8f12d..baef7372d 100644--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@ -418,6 +418,50 @@ class LearnerProfile(BaseModel):)+ReadingExtensionResultType = Literal[+ "card",+ "quiz",+ "feedback",+ "browser_speech",+]+++class ReadingProgressRecord(BaseModel):+ """One material's Reading progress in an account's learning records."""++ model_config = ConfigDict(extra="ignore")++ material_id: str+ latest_locator: int = Field(ge=1)+ latest_percentage: float = Field(ge=0.0, le=1.0)+ furthest_locator: int = Field(ge=1)+ furthest_percentage: float = Field(ge=0.0, le=1.0)+ updated_at: float = Field(default_factory=time.time)+++class ReadingActivityRecord(BaseModel):+ """One successful Reading-extension action, without source content."""++ model_config = ConfigDict(extra="ignore")++ activity_id: str+ material_id: str+ extension_id: str+ action: str+ locator: int = Field(ge=1)+ result_type: ReadingExtensionResultType+ created_at: float = Field(default_factory=time.time)+++class ReadingLearningRecords(BaseModel):+ """Account-scoped Reading summary for reporting surfaces."""++ model_config = ConfigDict(extra="ignore")++ progress: list[ReadingProgressRecord] = Field(default_factory=list)+ activities: list[ReadingActivityRecord] = Field(default_factory=list)++class LearningProgress(BaseModel):model_config = ConfigDict(extra="ignore")@@ -485,5 +529,8 @@ __all__ = ["TopicMetadata","MasteryTopic","LearnerMasteryOverride",+ "ReadingActivityRecord",+ "ReadingLearningRecords",+ "ReadingProgressRecord","LearningProgress",]diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.pyindex 154dd1b82..c20529aef 100644--- a/deeptutor/learning/storage.py+++ b/deeptutor/learning/storage.py@@ -1,4 +1,4 @@-"""Transactional persistence for Mastery Path aggregates.+"""Transactional persistence for Mastery Path and Reading learning records.The original implementation rewrote one JSON file per path. A process-locallock made each individual replace atomic, but two sessions could still load@@ -24,6 +24,7 @@ import sqlite3import threadingimport timefrom typing import Any, TypeVar+import uuidfrom pydantic import ValidationError@@ -34,6 +35,9 @@ from deeptutor.learning.models import (MasteryInteraction,MasteryPathLease,MasteryTopic,+ ReadingActivityRecord,+ ReadingLearningRecords,+ ReadingProgressRecord,TopicMetadata,TopicSource,)@@ -459,6 +463,29 @@ class LearningStore:);CREATE INDEX IF NOT EXISTS idx_mastery_topic_sources_pathON mastery_topic_sources(path_id, position);++ CREATE TABLE IF NOT EXISTS reading_progress (+ material_id TEXT PRIMARY KEY,+ latest_locator INTEGER NOT NULL,+ latest_percentage REAL NOT NULL,+ furthest_locator INTEGER NOT NULL,+ furthest_percentage REAL NOT NULL,+ updated_at REAL NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_reading_progress_updated+ ON reading_progress(updated_at DESC);++ CREATE TABLE IF NOT EXISTS reading_activities (+ activity_id TEXT PRIMARY KEY,+ material_id TEXT NOT NULL,+ extension_id TEXT NOT NULL,+ action TEXT NOT NULL,+ locator INTEGER NOT NULL,+ result_type TEXT NOT NULL,+ created_at REAL NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_reading_activities_recent+ ON reading_activities(created_at DESC, activity_id DESC);""")self._converge_single_membership(conn)@@ -972,6 +999,183 @@ class LearningStore:}return sorted(stored | legacy)+ # ---- account Reading learning records --------------------------------++ @staticmethod+ def _reading_progress_from_row(row: sqlite3.Row) -> ReadingProgressRecord:+ return ReadingProgressRecord(+ material_id=str(row["material_id"]),+ latest_locator=int(row["latest_locator"]),+ latest_percentage=float(row["latest_percentage"]),+ furthest_locator=int(row["furthest_locator"]),+ furthest_percentage=float(row["furthest_percentage"]),+ updated_at=float(row["updated_at"]),+ )++ @staticmethod+ def _reading_activity_from_row(row: sqlite3.Row) -> ReadingActivityRecord:+ return ReadingActivityRecord(+ activity_id=str(row["activity_id"]),+ material_id=str(row["material_id"]),+ extension_id=str(row["extension_id"]),+ action=str(row["action"]),+ locator=int(row["locator"]),+ result_type=str(row["result_type"]),+ created_at=float(row["created_at"]),+ )++ def record_reading_position(+ self,+ material_id: str,+ *,+ locator: int,+ percentage: float,+ ) -> ReadingProgressRecord:+ """Persist the latest viewport while preserving the furthest progress."""++ material_id = self._validate_id(material_id)+ locator = int(locator)+ percentage = float(percentage)+ record = ReadingProgressRecord(+ material_id=material_id,+ latest_locator=locator,+ latest_percentage=percentage,+ furthest_locator=locator,+ furthest_percentage=percentage,+ )+ now = time.time()+ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ try:+ row = conn.execute(+ """+ SELECT furthest_locator, furthest_percentage+ FROM reading_progress WHERE material_id = ?+ """,+ (material_id,),+ ).fetchone()+ if row is None:+ conn.execute(+ """+ INSERT INTO reading_progress (+ material_id, latest_locator, latest_percentage,+ furthest_locator, furthest_percentage, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?)+ """,+ (+ material_id,+ record.latest_locator,+ record.latest_percentage,+ record.furthest_locator,+ record.furthest_percentage,+ now,+ ),+ )+ else:+ record.furthest_locator = max(+ record.furthest_locator, int(row["furthest_locator"])+ )+ record.furthest_percentage = max(+ record.furthest_percentage,+ float(row["furthest_percentage"]),+ )+ conn.execute(+ """+ UPDATE reading_progress+ SET latest_locator = ?, latest_percentage = ?,+ furthest_locator = ?, furthest_percentage = ?,+ updated_at = ?+ WHERE material_id = ?+ """,+ (+ record.latest_locator,+ record.latest_percentage,+ record.furthest_locator,+ record.furthest_percentage,+ now,+ material_id,+ ),+ )+ record.updated_at = now+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ return record++ def record_reading_activity(+ self,+ material_id: str,+ *,+ extension_id: str,+ action: str,+ locator: int,+ result_type: str,+ ) -> ReadingActivityRecord:+ """Record one successful Reading-extension action without source content."""++ material_id = self._validate_id(material_id)+ extension_id = str(extension_id or "").strip()+ action = str(action or "").strip()+ if not extension_id or len(extension_id) > 64:+ raise ValueError("extension_id must contain 1 to 64 characters")+ if not action or len(action) > 64:+ raise ValueError("action must contain 1 to 64 characters")+ record = ReadingActivityRecord(+ activity_id=f"racc_{uuid.uuid4().hex}",+ material_id=material_id,+ extension_id=extension_id,+ action=action,+ locator=int(locator),+ result_type=result_type,+ )+ now = time.time()+ record.created_at = now+ with self._connect() as conn:+ conn.execute(+ """+ INSERT INTO reading_activities (+ activity_id, material_id, extension_id, action, locator,+ result_type, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ record.activity_id,+ record.material_id,+ record.extension_id,+ record.action,+ record.locator,+ record.result_type,+ now,+ ),+ )+ conn.commit()+ return record++ def list_reading_records(self, *, activity_limit: int = 200) -> ReadingLearningRecords:+ """Return this workspace's Reading progress and recent activity."""++ limit = max(1, min(int(activity_limit), 500))+ with self._connect() as conn:+ progress_rows = conn.execute(+ """+ SELECT * FROM reading_progress+ ORDER BY updated_at DESC, material_id ASC+ """+ ).fetchall()+ activity_rows = conn.execute(+ """+ SELECT * FROM reading_activities+ ORDER BY created_at DESC, activity_id DESC+ LIMIT ?+ """,+ (limit,),+ ).fetchall()+ return ReadingLearningRecords(+ progress=[self._reading_progress_from_row(row) for row in progress_rows],+ activities=[self._reading_activity_from_row(row) for row in activity_rows],+ )+# ---- product topic metadata -----------------------------------------@staticmethoddiff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex f7f906473..c8d30ff38 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -51,6 +51,39 @@ def _module_payload(module_id: str = "m1", kp_id: str = "kp1") -> dict:# -- GET /progress (list_all) --------------------------------------------+class TestReadingLearningRecords:+ def test_summary_returns_progress_and_activity(self, app, client):+ store = LearningStore(root=app.state.learning_root)+ store.record_reading_position("rm_one", locator=3, percentage=0.3)+ store.record_reading_activity(+ "rm_one",+ extension_id="sample",+ action="open",+ locator=3,+ result_type="card",+ )++ response = client.get("/api/mastery-paths/reading/records")++ assert response.status_code == 200, response.text+ data = response.json()+ assert data["progress"] == [+ {+ "material_id": "rm_one",+ "latest_locator": 3,+ "latest_percentage": 0.3,+ "furthest_locator": 3,+ "furthest_percentage": 0.3,+ "updated_at": data["progress"][0]["updated_at"],+ }+ ]+ assert len(data["activities"]) == 1+ assert data["activities"][0]["material_id"] == "rm_one"+ assert data["activities"][0]["extension_id"] == "sample"+ assert data["activities"][0]["action"] == "open"+ assert data["activities"][0]["result_type"] == "card"++class TestListProgress:def test_list_runs_blocking_store_work_in_worker_thread(self, client):with patch(diff --git a/deeptutor/learning/tests/test_storage.py b/deeptutor/learning/tests/test_storage.pyindex 8e02d30e5..11a4ded95 100644--- a/deeptutor/learning/tests/test_storage.py+++ b/deeptutor/learning/tests/test_storage.py@@ -4,6 +4,7 @@ from pathlib import Pathimport sqlite3import time+from pydantic import ValidationErrorimport pytestfrom deeptutor.learning.models import (@@ -562,6 +563,88 @@ class TestInteractionsAndEvents:assert persisted.status == InteractionStatus.GRADED+# ── Reading learning records ─────────────────────────────────────────────+++class TestReadingLearningRecords:+ def test_reading_tables_migrate_into_an_existing_learning_database(self, tmp_path):+ db_path = tmp_path / LearningStore._DB_FILENAME+ with sqlite3.connect(db_path) as conn:+ conn.execute(+ """+ CREATE TABLE mastery_paths (+ path_id TEXT PRIMARY KEY,+ state_json TEXT NOT NULL,+ revision INTEGER NOT NULL,+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL+ )+ """+ )++ store = LearningStore(root=tmp_path)+ store.record_reading_position("rm_one", locator=1, percentage=0.1)++ assert store.list_reading_records().progress[0].material_id == "rm_one"++ def test_position_progress_keeps_latest_and_furthest_views(self, store):+ first = store.record_reading_position("rm_one", locator=3, percentage=0.3)+ assert first.latest_locator == first.furthest_locator == 3++ second = store.record_reading_position("rm_one", locator=5, percentage=0.5)+ store.record_reading_position("rm_one", locator=4, percentage=0.4)++ records = store.list_reading_records()+ assert len(records.progress) == 1+ assert records.progress[0].material_id == "rm_one"+ assert records.progress[0].latest_locator == 4+ assert records.progress[0].latest_percentage == 0.4+ assert records.progress[0].furthest_locator == 5+ assert records.progress[0].furthest_percentage == 0.5++ def test_activity_records_keep_metadata_without_source_content(self, store):+ first = store.record_reading_activity(+ "rm_one",+ extension_id="guided_learning",+ action="guide",+ locator=2,+ result_type="card",+ )+ second = store.record_reading_activity(+ "rm_one",+ extension_id="vocabulary",+ action="explain",+ locator=3,+ result_type="card",+ )++ records = store.list_reading_records()+ assert {row.activity_id for row in records.activities} == {+ first.activity_id,+ second.activity_id,+ }+ assert all(row.material_id == "rm_one" for row in records.activities)+ assert all("visible_text" not in row.model_dump() for row in records.activities)++ def test_activity_result_type_is_schema_bounded(self, store):+ with pytest.raises(ValidationError):+ store.record_reading_activity(+ "rm_one",+ extension_id="sample",+ action="open",+ locator=1,+ result_type="javascript",+ )++ def test_reading_ids_and_values_are_validated(self, store):+ with pytest.raises(ValueError, match="Invalid book_id"):+ store.record_reading_position("../escape", locator=1, percentage=0.1)+ with pytest.raises(ValidationError):+ store.record_reading_position("rm_one", locator=0, percentage=0.1)+ with pytest.raises(ValidationError):+ store.record_reading_position("rm_one", locator=1, percentage=1.1)++# ── atomic write ──────────────────────────────────────────────────────────diff --git a/tests/multi_user/test_learning_records_isolation.py b/tests/multi_user/test_learning_records_isolation.pynew file mode 100644index 000000000..da0a90bfb--- /dev/null+++ b/tests/multi_user/test_learning_records_isolation.py@@ -0,0 +1,45 @@+from pathlib import Path++from deeptutor.learning.storage import LearningStore+from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.models import CurrentUser, UserScope+++def _user(root: Path, user_id: str) -> CurrentUser:+ user_root = root / "users" / user_id+ return CurrentUser(+ id=user_id,+ username=user_id,+ role="user",+ scope=UserScope(kind="user", user_id=user_id, root=user_root),+ )+++def test_reading_learning_records_stay_in_each_users_workspace(tmp_path: Path) -> None:+ stores = {}+ for user_id in ("u_alice", "u_bob"):+ token = set_current_user(_user(tmp_path, user_id))+ try:+ store = LearningStore()+ stores[user_id] = store+ store.record_reading_position(+ "rm_shared", locator=2 if user_id == "u_alice" else 1, percentage=0.5+ )+ store.record_reading_activity(+ "rm_shared",+ extension_id="sample",+ action="open",+ locator=1,+ result_type="card",+ )+ finally:+ reset_current_user(token)++ records = store.list_reading_records()+ assert records.progress[0].material_id == "rm_shared"+ assert records.progress[0].furthest_locator == (2 if user_id == "u_alice" else 1)+ assert records.activities[0].activity_id++ assert stores["u_alice"].db_path != stores["u_bob"].db_path+ assert stores["u_alice"].list_reading_records().progress[0].furthest_locator == 2+ assert stores["u_bob"].list_reading_records().progress[0].furthest_locator == 1diff --git a/tests/reading/test_extension_router.py b/tests/reading/test_extension_router.pyindex c650f4c15..10bd26ec3 100644--- a/tests/reading/test_extension_router.py+++ b/tests/reading/test_extension_router.py@@ -10,6 +10,7 @@ from fastapi.testclient import TestClientimport pytestfrom deeptutor.api.routers import reading_extensions+from deeptutor.learning.storage import LearningStorefrom deeptutor.reading import ReadingStorefrom deeptutor.reading.extensions import (ReadingAction,@@ -78,6 +79,14 @@ def test_action_receives_only_server_verified_visible_text(material, monkeypatchassert response.status_code == 200, response.textassert captured["selection"] == ""assert captured["visible_text"] == "Visible passage with a verified phrase."+ records = LearningStore().list_reading_records()+ assert len(records.activities) == 1+ assert records.activities[0].material_id == material.material_id+ assert records.activities[0].extension_id == "sample"+ assert records.activities[0].action == "open"+ assert records.activities[0].locator == 1+ assert records.activities[0].result_type == "card"+ assert "visible_text" not in records.activities[0].model_dump()def test_source_anchor_is_loaded_from_server_position(material, monkeypatch):@@ -145,6 +154,7 @@ def test_extension_failures_are_isolated(material, monkeypatch, run_action):)assert response.status_code == 503assert response.json()["detail"]["recoverable"] is True+ assert LearningStore().list_reading_records().activities == []def test_hanging_extension_action_times_out(material, monkeypatch):diff --git a/tests/reading/test_router.py b/tests/reading/test_router.pyindex e59d78266..d44166de2 100644--- a/tests/reading/test_router.py+++ b/tests/reading/test_router.py@@ -15,6 +15,7 @@ from fastapi.testclient import TestClientimport pytestfrom deeptutor.api.routers import reading+from deeptutor.learning.storage import LearningStorefrom deeptutor.reading import ReadingCatalogStore, ReadingError, ReadingStorefrom deeptutor.services.path_service import PathService@@ -354,6 +355,31 @@ def test_epub_contract_exposes_source_refs_original_and_position(client: TestCliassert client.put(base, json={"locator": 2, "percentage": 0}).status_code == 400+def test_saved_reading_position_updates_account_learning_record(client: TestClient) -> None:+ material = _upload(client)+ base = f"/api/reading/materials/{material['material_id']}/position"++ assert client.put(base, json={"locator": 1, "percentage": 0.2}).status_code == 200+ assert client.put(base, json={"locator": 2, "percentage": 0.7}).status_code == 200+ assert (+ client.put(+ base,+ json={"locator": 1, "source_anchor": "private-anchor", "percentage": 0.3},+ ).status_code+ == 200+ )++ records = LearningStore().list_reading_records()+ assert len(records.progress) == 1+ progress = records.progress[0]+ assert progress.material_id == material["material_id"]+ assert progress.latest_locator == 1+ assert progress.latest_percentage == 0.3+ assert progress.furthest_locator == 2+ assert progress.furthest_percentage == 0.7+ assert "source_anchor" not in progress.model_dump()++def test_epub_pairing_requires_confirmation_and_preserves_source_materials(client: TestClient,) -> None: