Skip to content

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

fix: ruff auto-fix (22 issues), mypy type fixes for KnowledgeType

whfa0ee477ff92d
diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.md
new file mode 100644
index 000000000..8e3af444f
--- /dev/null
+++ b/PR_DESCRIPTION.md
@@ -0,0 +1,82 @@
+# feat: Guided Learning — structured mastery-based tutoring system
+
+## Summary
+
+This PR introduces **Guided Learning**, a structured, mastery-based tutoring subsystem that transforms DeepTutor from a free-form chat tool into a pedagogical learning system with persistent progress tracking, spaced repetition, and adaptive stage progression.
+
+**Upstream status**: This is a complete new subsystem. `upstream/main` has no `deeptutor/learning/`, no `guided_learning.py` capability, and no learning-related frontend pages or components.
+
+**Scope**: 73 files changed, +11,590 / -4,491 lines. All changes are additive except for minor hook points in existing chat/stream infrastructure.
+
+---
+
+## What’s included
+
+### Backend
+
+| Component | Files | Description |
+|-----------|-------|-------------|
+| **Models** | `deeptutor/learning/models.py` | 4 enums + 9 Pydantic models: `LearningProgress`, `LearningModule`, `KnowledgePoint`, `QuizAttempt`, `ErrorRecord`, etc. |
+| **Storage** | `deeptutor/learning/storage.py` | JSON persistence with CAS (compare-and-swap) semantics and path-traversal guards |
+| **Service** | `deeptutor/learning/service.py` | Business logic: module lifecycle, mastery calculation (weighted recent accuracy), quiz attempt recording, error tracking |
+| **Scheduler** | `deeptutor/learning/scheduler.py` | Spaced repetition scheduler with per-knowledge-type initial states |
+| **Grading** | `deeptutor/learning/grading.py` | Server-side answer evaluation with normalization and stripping |
+| **Capability** | `deeptutor/capabilities/guided_learning.py` | 12-stage state machine: diagnostic → plan → pretest → explain → Feynman check → practice → error diagnosis → module test → review → completed |
+| **API Router** | `deeptutor/api/routers/guided_learning.py` | 13 REST endpoints: progress CRUD, module generation, notebook import, `/redo`, `/answer`, etc. |
+| **Tests** | `deeptutor/learning/tests/` (14 files) | 164 tests covering models, storage, scheduler, service, API endpoints, LLM integration, timeout degradation, error diagnosis, E2E flow |
+
+### Frontend
+
+| Component | Files | Description |
+|-----------|-------|-------------|
+| **Learning Pages** | `web/app/(workspace)/learning/` | Module list, book-based learning session, WebSocket-driven stage streaming |
+| **Learning Components** | `web/components/learning/` | `ModuleTree` (sidebar + mastery indicator), `CreateModuleDialog` (4-tab module creation), `StructuredStageContent` (JSON content rendering) |
+| **API Client** | `web/lib/learning-api.ts` | Typed API client for all learning endpoints |
+| **i18n** | `web/locales/en/app.json`, `zh/app.json` | Full English + Chinese localization |
+
+### Infrastructure hooks
+
+- `deeptutor/core/stream_bus.py`: added `wait_for_input()` for interactive stage turns
+- `deeptutor/api/routers/unified_ws.py`: wired Guided Learning into WebSocket routing
+- `deeptutor/api/main.py`: registered learning router
+
+---
+
+## Key design decisions
+
+1. **Fail-closed + degradation**: Every LLM call has bounded retry + timeout. If a stage fails repeatedly, it degrades gracefully (skips with user-visible notice) rather than blocking the learner.
+2. **Cross-turn persistence**: `LearningProgress` is saved after every interactive step, so reconnects, cancellations, and backend restarts never lose student attempts.
+3. **Server-side grading**: All answer evaluation happens server-side with stripped comparisons, preventing client-side manipulation.
+4. **Prompt injection hardening**: Notebook-to-module generation uses XML tag boundaries (`<notebook_records>`), system-prompt constraints, input escaping (`html.escape` on user fields), and output validation (type whitelist + length truncation).
+
+---
+
+## Testing
+
+```bash
+cd deeptutor/learning/tests
+pytest -q
+# 164 passed in ~3s
+```
+
+Test categories:
+- Unit: models, storage, scheduler, grading
+- Integration: service replace/merge, mastery updates, timeout degradation
+- API: all 13 endpoints with success + error paths
+- E2E: complete `PRETEST → EXPLAIN → FEYNMAN_CHECK → PRACTICE_QUIZ → ERROR_DIAGNOSIS → MODULE_TEST → REVIEW → COMPLETED` flow
+
+---
+
+## Checklist
+
+- [x] 164 tests pass
+- [x] No breaking changes to existing chat / solve / research capabilities
+- [x] i18n parity verified (`npm run i18n:parity`)
+- [x] No secrets or local configs committed
+- [x] All user-facing strings localized
+
+---
+
+## Related
+
+Closes the gap identified in community discussions around structured learning workflows (see Discord #feature-requests, Feishu group).
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index f74e2fcbb..8df0062d3 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -24,7 +24,6 @@ History compression (branch-safe) is handled upstream by
from __future__ import annotations
import asyncio
-import json
import logging
from typing import Any
diff --git a/deeptutor/api/routers/guided_learning.py b/deeptutor/api/routers/guided_learning.py
index 481d98f35..e97dfbc35 100644
--- a/deeptutor/api/routers/guided_learning.py
+++ b/deeptutor/api/routers/guided_learning.py
@@ -13,6 +13,7 @@ from deeptutor.learning.grading import grade_answer
from deeptutor.learning.models import (
ErrorType,
KnowledgePoint,
+ KnowledgeType,
LearningModule,
LearningStage,
QuizAttempt,
@@ -256,7 +257,7 @@ async def import_from_book(book_id: str, body: ImportFromBookRequest):
modules = []
for i, ch in enumerate(body.chapters):
kps = [
- KnowledgePoint(id=f"{book_id}_ch{i}_kp{j}", name=kp_name, type="concept", module_id=f"{book_id}_ch{i}")
+ KnowledgePoint(id=f"{book_id}_ch{i}_kp{j}", name=kp_name, type=KnowledgeType("concept"), module_id=f"{book_id}_ch{i}")
for j, kp_name in enumerate(ch.knowledge_points)
]
modules.append(LearningModule(
@@ -389,7 +390,7 @@ type 可选:memory / concept / procedure / design。
kps.append(KnowledgePoint(
id=f"{book_id}_nb{i}_kp{j}",
name=kp_name,
- type=kp_type,
+ type=KnowledgeType(kp_type),
module_id=f"{book_id}_nb{i}",
))
modules.append(LearningModule(
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 1892fe5fb..0abb1ea1e 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -262,9 +262,9 @@ async def unified_websocket(ws: WebSocket) -> None:
if not session_id or not module_id:
await safe_send({"type": "error", "content": "Missing session_id or module_id for change_module."})
continue
+ from deeptutor.learning.models import LearningStage
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
- from deeptutor.learning.models import LearningStage
from deeptutor.services.session import get_turn_runtime_manager
store = LearningStore()
diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.py
index 50aafd09a..ba2afdfb3 100644
--- a/deeptutor/book/storage.py
+++ b/deeptutor/book/storage.py
@@ -84,7 +84,6 @@ class BookStorage:
@property
def path_service(self):
- from deeptutor.services.path_service import get_path_service
return get_path_service()
# ── Path helpers ─────────────────────────────────────────────────────
@@ -270,7 +269,6 @@ _storages: dict[str, BookStorage] = {}
def get_book_storage() -> BookStorage:
- from deeptutor.services.path_service import get_path_service
key = str(get_path_service().workspace_root.resolve())
if key not in _storages:
_storages[key] = BookStorage()
diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.py
index 038eea107..1a1b30f71 100644
--- a/deeptutor/capabilities/guided_learning.py
+++ b/deeptutor/capabilities/guided_learning.py
@@ -2,8 +2,8 @@
from __future__ import annotations
-import contextvars
import asyncio
+import contextvars
import json
import time
from typing import Any
@@ -17,16 +17,11 @@ from deeptutor.learning.grading import grade_answer
from deeptutor.learning.models import (
DiagnosticResult,
ErrorType,
- KnowledgePoint,
KnowledgeType,
- LearningModule,
LearningProgress,
LearningStage,
QuizAttempt,
)
-from deeptutor.learning.scheduler import SpacedRepetitionScheduler
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
from deeptutor.learning.prompts import (
DIAGNOSTIC_PHASE1_SYSTEM,
DIAGNOSTIC_PHASE1_USER,
@@ -53,6 +48,9 @@ from deeptutor.learning.prompts import (
REVIEW_SYSTEM,
REVIEW_USER,
)
+from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+from deeptutor.learning.service import LearningService
+from deeptutor.learning.storage import LearningStore
from deeptutor.services.llm import complete
diff --git a/deeptutor/learning/grading.py b/deeptutor/learning/grading.py
index 7ea02e3e4..a9d690146 100644
--- a/deeptutor/learning/grading.py
+++ b/deeptutor/learning/grading.py
@@ -1,8 +1,8 @@
"""Unified grading function for guided learning."""
from __future__ import annotations
-import re
from difflib import SequenceMatcher
+import re
def grade_answer(user_answer: str, expected_answer: str, question_type: str = "short") -> bool:
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index 4245f1cdf..f790a520b 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -1,12 +1,11 @@
from __future__ import annotations
-import time
from enum import Enum
+import time
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
-
_KNOWLEDGE_TYPE_LEGACY: dict[str, str] = {
"记忆型": "memory",
"概念型": "concept",
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 51436c861..a0ee01fa5 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -1,9 +1,9 @@
from __future__ import annotations
+from pathlib import Path
import threading
import time
import uuid
-from pathlib import Path
from deeptutor.learning.models import LearningProgress
from deeptutor.services.path_service import get_path_service
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index 21456ebaa..58d0c95a7 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -3,11 +3,12 @@
import json
from unittest.mock import AsyncMock, patch
-import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
+import pytest
+
from deeptutor.api.routers.guided_learning import router
-from deeptutor.learning.models import LearningModule, KnowledgePoint, KnowledgeType
+from deeptutor.learning.models import KnowledgePoint, KnowledgeType, LearningModule
from deeptutor.learning.storage import LearningStore
diff --git a/deeptutor/learning/tests/test_e2e_flow.py b/deeptutor/learning/tests/test_e2e_flow.py
index 0acc5c486..6b852c369 100644
--- a/deeptutor/learning/tests/test_e2e_flow.py
+++ b/deeptutor/learning/tests/test_e2e_flow.py
@@ -1,7 +1,7 @@
"""End-to-end flow test: PRETEST → EXPLAIN → FEYNMAN_CHECK → PRACTICE_QUIZ → ERROR_DIAGNOSIS → MODULE_TEST → REVIEW → COMPLETED."""
-import json
from contextlib import asynccontextmanager
+import json
from unittest.mock import AsyncMock
import pytest
diff --git a/deeptutor/learning/tests/test_feynman_retry.py b/deeptutor/learning/tests/test_feynman_retry.py
index bbaeee4f8..6def59dc7 100644
--- a/deeptutor/learning/tests/test_feynman_retry.py
+++ b/deeptutor/learning/tests/test_feynman_retry.py
@@ -1,8 +1,8 @@
"""Tests for Feynman check retry limit."""
import asyncio
-import json
from contextlib import asynccontextmanager
+import json
from unittest.mock import AsyncMock, patch
import pytest
diff --git a/deeptutor/learning/tests/test_guided_mastery_updates.py b/deeptutor/learning/tests/test_guided_mastery_updates.py
index aae7c2940..20a4ca811 100644
--- a/deeptutor/learning/tests/test_guided_mastery_updates.py
+++ b/deeptutor/learning/tests/test_guided_mastery_updates.py
@@ -1,7 +1,13 @@
"""Tests for Guided Learning mastery updates from in-turn answers."""
from deeptutor.capabilities.guided_learning import GuidedLearningCapability
-from deeptutor.learning.models import KnowledgePoint, KnowledgeType, LearningModule, LearningProgress, QuizAttempt
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ LearningProgress,
+ QuizAttempt,
+)
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
diff --git a/deeptutor/learning/tests/test_llm_integration.py b/deeptutor/learning/tests/test_llm_integration.py
index 6904cbaf0..05169fa46 100644
--- a/deeptutor/learning/tests/test_llm_integration.py
+++ b/deeptutor/learning/tests/test_llm_integration.py
@@ -1,7 +1,9 @@
"""Integration tests for guided_learning LLM + RAG integration."""
+from unittest.mock import AsyncMock, MagicMock, patch
+
import pytest
-from unittest.mock import AsyncMock, patch, MagicMock
+
from deeptutor.capabilities.guided_learning import GuidedLearningCapability
from deeptutor.learning.models import LearningProgress, LearningStage
diff --git a/deeptutor/learning/tests/test_models.py b/deeptutor/learning/tests/test_models.py
index c2622e6be..3a2b25b26 100644
--- a/deeptutor/learning/tests/test_models.py
+++ b/deeptutor/learning/tests/test_models.py
@@ -16,7 +16,6 @@ from deeptutor.learning.models import (
ReviewTask,
)
-
# ── Enums ────────────────────────────────────────────────────────────────
class TestKnowledgeType:
diff --git a/deeptutor/learning/tests/test_storage.py b/deeptutor/learning/tests/test_storage.py
index 4360dd76d..e5f1ea5a8 100644
--- a/deeptutor/learning/tests/test_storage.py
+++ b/deeptutor/learning/tests/test_storage.py
@@ -1,6 +1,6 @@
+from pathlib import Path
import tempfile
import time
-from pathlib import Path
import pytest
diff --git a/deeptutor/services/rag/pipelines/llamaindex/config.py b/deeptutor/services/rag/pipelines/llamaindex/config.py
index 713911109..a7d43ca74 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/config.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/config.py
@@ -5,7 +5,6 @@ from __future__ import annotations
from dataclasses import dataclass
import os
-
VECTOR_PROFILE = "vector"
HYBRID_PROFILE = "hybrid"
SUPPORTED_RETRIEVAL_PROFILES = {VECTOR_PROFILE, HYBRID_PROFILE}
diff --git a/deeptutor/services/session/source_inventory.py b/deeptutor/services/session/source_inventory.py
index 841be4564..5e6255e8e 100644
--- a/deeptutor/services/session/source_inventory.py
+++ b/deeptutor/services/session/source_inventory.py
@@ -29,8 +29,8 @@ The output is decoupled from the rest of ``turn_runtime``:
from __future__ import annotations
-import logging
from dataclasses import dataclass, field
+import logging
from typing import Any, Sequence
from deeptutor.services.session.protocol import SessionStoreProtocol
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index b85a8584d..cb59dce16 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -196,7 +196,6 @@ class TutorBotManager:
@property
def _path_service(self):
- from deeptutor.services.path_service import get_path_service
return get_path_service()
# ── Path helpers ──────────────────────────────────────────────
@@ -1119,7 +1118,6 @@ _managers: dict[str, TutorBotManager] = {}
def get_tutorbot_manager() -> TutorBotManager:
- from deeptutor.services.path_service import get_path_service
key = str(get_path_service().workspace_root.resolve())
if key not in _managers:
_managers[key] = TutorBotManager()