Skip to content

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

daily update

Bingxi Zhao (Frank)04cc156fa83c
diff --git a/README.md b/README.md
index 7e2ff7925..be364ed72 100644
--- a/README.md
+++ b/README.md
@@ -34,7 +34,7 @@
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
-[Features](#-key-features) · [Get Started](#-get-started) · [Explore](#-explore-deeptutor) · [CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) · [Multi-User](#-multi-user--shared-deployments) · [Community](#-community--ecosystem)
+[Features](#-key-features) · [Get Started](#-get-started) · [Explore](#-explore-deeptutor) · [CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) · [Multi-User](#-multi-user--shared-deployments) · [Community](#-community)
</div>
@@ -173,7 +173,8 @@ DeepTutor ships four installation paths. They all share one workspace layout: se
> ✨ **v1.4.4 is live.** `pip install -U deeptutor` picks up the latest stable. Pre-releases (when available) opt in with `pip install --pre -U deeptutor`.
-### Option 1 — Install From PyPI
+<details>
+<summary><b>Option 1 — Install From PyPI</b></summary>
Full local Web app + CLI, no clone required. Needs **Python 3.11+** and a **Node.js 20+** runtime on PATH (the packaged Next.js standalone server is spawned by `deeptutor start`).
@@ -188,7 +189,10 @@ deeptutor start # starts backend + frontend; keep the terminal open
After `deeptutor start`, open the frontend URL printed in the terminal — by default [http://127.0.0.1:3782](http://127.0.0.1:3782). Press `Ctrl+C` in that terminal to stop both backend and frontend. Skipping `deeptutor init` is fine for a quick trial; the app boots with default ports and empty model settings, configure them later in **Settings → Models**.
-### Option 2 — Install From Source
+</details>
+
+<details>
+<summary><b>Option 2 — Install From Source</b></summary>
For development against a checkout. Use **Python 3.11+** and **Node.js 22 LTS** to match CI and Docker.
@@ -249,7 +253,10 @@ deeptutor start
</details>
-### Option 3 — Docker
+</details>
+
+<details>
+<summary><b>Option 3 — Docker</b></summary>
One container for the full Web app. Images on GitHub Container Registry:
@@ -319,6 +326,8 @@ Docker Desktop (macOS/Windows) usually resolves `host.docker.internal` without `
</details>
+</details>
+
### Code Execution Sandbox (office skills)
The built-in office skills — **docx / pdf / pptx / xlsx** — work by having the
@@ -340,7 +349,8 @@ on your host is a real trust decision — set it to `false` (or export
`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) to disable host-side execution, at the
cost of the office skills no longer being able to produce files.
-### Option 4 — CLI Only
+<details>
+<summary><b>Option 4 — CLI Only</b></summary>
When you don't need the Web UI. The CLI-only package is installed from a source checkout, not from PyPI.
@@ -377,6 +387,8 @@ deeptutor config show
The local `deeptutor-cli` install ships no Web assets or server dependencies. Keep the source checkout around — the editable install points to it. To add the Web app later, install the PyPI package (Option 1) and run `deeptutor init` + `deeptutor start` from the same workspace.
+</details>
+
### Configuration Reference
<details>
@@ -402,7 +414,8 @@ Project-root `.env` is **not** read as an application config file. For a minimal
The README tour follows the product surfaces in the order you will most often meet them: Chat, Partner, Co-Writer, Book, Knowledge, Space, Memory, and Settings. The screenshots below come from the reorganized `assets/figs` tree; archived legacy images are intentionally not used here.
-### 💬 Chat — The Agent Loop You Actually Use
+<details>
+<summary><b>💬 Chat — The Agent Loop You Actually Use</b></summary>
<div align="center">
<img src="assets/figs/webui/chat.png" alt="DeepTutor chat workspace" width="900">
@@ -418,7 +431,10 @@ The current loop is deliberately simple: the model thinks in rounds, calls tools
Chat is also the launch point for deeper capabilities: `deep_solve` for worked reasoning, `deep_question` for question generation, `deep_research` for cited reports, `visualize` and `math_animator` for visual outputs, `auto` for routing, and `mastery_path` for learning-plan flows.
-### 🤝 Partner — Persistent Companions on the Same Brain
+</details>
+
+<details>
+<summary><b>🤝 Partner — Persistent Companions on the Same Brain</b></summary>
<div align="center">
<img src="assets/figs/webui/partners.png" alt="DeepTutor partners workspace" width="900">
@@ -438,13 +454,19 @@ Each partner has a `SOUL.md`, model selection, channels, tool policy, and assign
The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, DingTalk, QQ/Napcat, WeCom, WhatsApp, Zulip, Matrix, and Microsoft Teams depending on installed extras and configured credentials.
-### ✍️ Co-Writer — Selection-Aware Markdown Drafting
+</details>
+
+<details>
+<summary><b>✍️ Co-Writer — Selection-Aware Markdown Drafting</b></summary>
Co-Writer is a split-view Markdown workspace for reports, tutorials, notes, and long-form learning artifacts. Documents autosave, render a live preview, and can be saved back into notebooks when the draft becomes reusable context.
Select text and ask DeepTutor to rewrite, expand, or shorten it. The edit agent keeps a trace of tool calls and can ground an edit in a knowledge base or web evidence, so Co-Writer behaves more like an editor with retrieval than a detached text box.
-### 📖 Book — Living Books from Your Materials
+</details>
+
+<details>
+<summary><b>📖 Book — Living Books from Your Materials</b></summary>
<p align="center">
<img src="assets/figs/webui/book01.png" alt="DeepTutor book reading view" width="31%">
@@ -458,7 +480,10 @@ Book turns selected sources into interactive learning material. A book can start
The BookEngine compiles pages into typed blocks: text, sections, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, and user notes. Maintenance commands such as `deeptutor book health` and `deeptutor book refresh-fingerprints` help detect when source knowledge has drifted from compiled pages.
-### 📚 Knowledge — Versioned RAG Libraries
+</details>
+
+<details>
+<summary><b>📚 Knowledge — Versioned RAG Libraries</b></summary>
<div align="center">
<img src="assets/figs/webui/knowledge.png" alt="DeepTutor knowledge base workspace" width="900">
@@ -468,7 +493,10 @@ Knowledge Bases are the document collections behind RAG. The current stack is Ll
The web workspace exposes files, upload, index versions, and settings. The CLI mirrors the same lifecycle with `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.
-### 🌐 Space — Skills, Personas, and Reusable Context
+</details>
+
+<details>
+<summary><b>🌐 Space — Skills, Personas, and Reusable Context</b></summary>
<div align="center">
<img src="assets/figs/webui/space.png" alt="DeepTutor space workspace" width="900">
@@ -478,7 +506,10 @@ Space is the library layer for reusable context. It brings together user-authore
Skills are stored as `SKILL.md` files under the user workspace and can be tagged, edited, or kept read-only when they are built in. Personas follow the same idea for role and voice. These assets can be assigned to partners, referenced in chat, and reused across learning workflows.
-### 🧠 Memory — Inspectable Personalization
+</details>
+
+<details>
+<summary><b>🧠 Memory — Inspectable Personalization</b></summary>
<div align="center">
<img src="assets/figs/webui/memory01.png" alt="DeepTutor memory workbench" width="900">
@@ -492,7 +523,10 @@ Memory is a three-layer system rooted in the active user workspace: `trace/<surf
The supported memory surfaces are `chat`, `notebook`, `quiz`, `kb`, `book`, `tutorbot`, and `cowriter`. The legacy `tutorbot` surface name remains in the memory layer for compatibility even though the product-facing companion model is now Partners. The workbench lets you inspect, edit, run consolidation, and use the graph to trace synthesized claims back to their supporting facts and raw events.
-### ⚙️ Settings — One Control Plane
+</details>
+
+<details>
+<summary><b>⚙️ Settings — One Control Plane</b></summary>
<div align="center">
<img src="assets/figs/webui/settings.png" alt="DeepTutor settings workspace" width="900">
@@ -502,6 +536,8 @@ Settings is the operational control plane. It covers appearance, network ports a
Most settings use a draft-and-apply flow so users can test providers before committing them. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.
+</details>
+
---
## ⌨️ DeepTutor CLI — Agent-Native Interface
@@ -601,22 +637,33 @@ ClawHub also distributes *plugins* (OpenClaw gateway runtime extensions); those
---
## 🌐 Community
-DeepTutor stands on the shoulders of outstanding open-source projects:
+### 📮 Contact
-| Project | Role in DeepTutor |
-|:---|:---|
-| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultra-lightweight agent engine that powered the original TutorBot (Partners now run on DeepTutor's chat agent loop) |
-| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAG pipeline and document indexing backbone |
-| [**ManimCat**](https://github.com/Wing900/ManimCat) | AI-driven math animation generation for Math Animator |
+DeepTutor is built and maintained by the [Data Intelligence Lab @ HKU](https://github.com/HKUDS), with ongoing contributions from the open-source community. Feel free to reach out at **[email protected]** for questions, ideas, or collaboration.
-**From the HKUDS ecosystem:**
+> ⚠️ DeepTutor's **only** official website is [**deeptutor.info**](https://deeptutor.info/). We do **not** run any hosted, paid, or otherwise online product of any kind — DeepTutor is open-source software you run on your own machine.
-| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🤖 AutoAgent](https://github.com/HKUDS/AutoAgent) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [🧬 nanobot](https://github.com/HKUDS/nanobot) |
-|:---:|:---:|:---:|:---:|
-| Simple & Fast RAG | Zero-Code Agent Framework | Automated Research | Ultra-Lightweight AI Agent |
+### 🙏 Appreciation
+Heartfelt thanks to the **[Data Intelligence Lab @ HKU](https://github.com/HKUDS)** — our professor and labmates — whose guidance and support make this work possible. And thank you to the **open-source community**: your stars, issues, pull requests, and discussions shape DeepTutor every single day.
-## 🤝 Contributing
+DeepTutor stands on the shoulders of outstanding open-source projects that gave us both tools and inspiration:
+
+| Project | Role / Inspiration |
+|:---|:---|
+| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAG pipeline and document-indexing backbone |
+| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultra-lightweight agent engine that powered the original TutorBot *(HKUDS)* |
+| [**ManimCat**](https://github.com/Wing900/ManimCat) | AI-driven math animation generation for Math Animator |
+| [**LightRAG**](https://github.com/HKUDS/LightRAG) | Simple & fast RAG *(HKUDS)* |
+| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Zero-code agent framework *(HKUDS)* |
+| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Automated research pipeline *(HKUDS)* |
+| [**OpenClaw**](https://github.com/openclaw/openclaw) | Open agent gateway and skill ecosystem behind ClawHub |
+| [**Codex**](https://github.com/openai/codex) | Agent-native coding CLI that inspired our CLI workflow |
+| [**Claude Code**](https://github.com/anthropics/claude-code) | Agentic coding CLI that inspired the DeepTutor agent loop |
+
+### 🗺️ Roadmap & Contribute
+
+We want DeepTutor to keep iterating and improving — and ultimately to become a gift we give back to the open-source community. 🎁 Our [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) is updated continuously; vote on items there or propose new ones. If you'd like to contribute, see the [**Contributing Guide**](CONTRIBUTING.md) for branching strategy, coding standards, and how to get started.
<div align="center">
@@ -628,10 +675,6 @@ We hope DeepTutor becomes a gift for the community. 🎁
</div>
-See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on setting up your development environment, code standards, and pull request workflow.
-
-## ⭐ Star History
-
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index 4147f9a87..c179886e9 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -25,6 +25,7 @@ from dataclasses import dataclass
from typing import Any
from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES, USER_TOGGLEABLE_TOOL_NAMES
+from deeptutor.tools.mastery_tool import MASTERY_TOOL_NAMES
# Tools whose mounting is owned by the pipeline (auto-on under specific
# context conditions), not by the user's composer toggles. Adding a tool
@@ -47,7 +48,7 @@ AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(
"github",
"cron",
}
-)
+).union(MASTERY_TOOL_NAMES)
def default_optional_tools(excluded: Iterable[str] = ()) -> list[str]:
@@ -84,6 +85,7 @@ class ToolMountFlags:
has_deferred_tools: bool = False
has_exec: bool = False
has_code: bool = False
+ has_mastery: bool = False
def compose_enabled_tools(
@@ -133,6 +135,8 @@ def compose_enabled_tools(
composed.append("exec")
if mount_flags.has_code:
composed.append("code_execution")
+ if mount_flags.has_mastery:
+ composed.extend(MASTERY_TOOL_NAMES)
composed.append("write_memory")
composed.append("web_fetch")
composed.append("github")
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index f2df9570b..d4231ea57 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -47,6 +47,7 @@ from deeptutor.services.llm import (
)
from deeptutor.services.llm.context_window import resolve_effective_context_window
from deeptutor.services.prompt import get_prompt_manager
+from deeptutor.tools.mastery_tool import MASTERY_TOOL_NAMES
logger = logging.getLogger(__name__)
@@ -62,6 +63,42 @@ DEFAULT_MAX_ROUNDS = 8
CONTEXT_WINDOW_GUARD_RATIO = 0.9
_DispatchOutcome = DispatchOutcome
+# The mastery-tutor playbook, injected as a system block only when the turn is
+# in mastery mode (set by MasteryPathCapability). The intelligence — what to
+# teach, how to question — lives here at the loop's exit; the hard gate and the
+# spaced-repetition arithmetic live in the engine the mastery tools call.
+_MASTERY_SYSTEM_EN = """\
+[Mastery Tutor mode]
+You are a one-on-one mastery tutor. The learner works through a map of objectives, each behind a HARD mastery gate: an objective counts as "mastered" only once its gate clears, and you must not move on until it does.
+
+FIRST on every turn, call `mastery_status`. It returns the next objective to work on, any question awaiting an answer, due reviews, and the full map. Trust it to choose the objective — never guess what comes next.
+
+Then act on the objective:
+- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).
+- `probe` (untouched): briefly check whether the learner already knows it before teaching — let them test out, don't lecture what they have already mastered.
+- memory / procedure objectives: pose a concrete question with `mastery_quiz`, present it (use `ask_user` for a tight ask-and-answer loop), then score the learner's answer with `mastery_grade`. Keep working the same objective until `mastery_grade` reports `mastered: true`.
+- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).
+- `review`: a spaced-repetition item is due — quiz it again to refresh it.
+- `complete`: congratulate the learner and summarise what they have mastered.
+
+Teach from the learner's own materials when available. Keep each turn focused on one objective. Be warm and encouraging, but hold the bar — clearing the gate is the point, not moving fast."""
+
+_MASTERY_SYSTEM_ZH = """\
+[精通导师模式]
+你是一对一的掌握式导师。学习者沿着一张知识点地图前进,每个知识点都有一道硬性掌握门槛:只有门槛达成,该知识点才算"已掌握",在此之前你绝不能推进到下一个。
+
+每一轮都要先调用 `mastery_status`。它会返回当前要攻克的知识点、是否有待批改的作答、到期复习项,以及整张地图。请信任它来决定学什么——绝不要自己猜下一个知识点。
+
+然后针对该知识点行动:
+- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。
+- `probe`(未触碰):先简短探查学习者是否已经会了再教——允许其"测试通过"直接跳过,不要重复讲他已掌握的内容。
+- memory / procedure 类:用 `mastery_quiz` 出一道具体题目并呈现给学习者(紧凑问答用 `ask_user`),再用 `mastery_grade` 批改其作答。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。
+- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。
+- `review`:有到期的间隔复习项——再考一次以巩固。
+- `complete`:祝贺学习者并总结其已掌握的内容。
+
+有材料时优先用学习者自己的材料来教。每一轮聚焦一个知识点。态度温暖鼓励,但守住门槛——目标是达成掌握,而非求快。"""
+
def _read_int(cfg: Any, *, key: str, default: int) -> int:
if isinstance(cfg, dict):
@@ -270,6 +307,7 @@ class AgenticChatPipeline:
),
notebook_manifest=self._build_notebook_manifest(),
workspace_note=self._workspace_system_note(context),
+ mastery_note=self._mastery_system_note(context),
include_tool_manifest=include_tool_manifest,
)
@@ -439,6 +477,7 @@ class AgenticChatPipeline:
has_deferred_tools=getattr(self, "_deferred_loader", None) is not None,
has_exec=getattr(self, "_exec_enabled", False),
has_code=getattr(self, "_exec_enabled", False),
+ has_mastery=self._mastery_active(context),
),
)
@@ -678,6 +717,10 @@ class AgenticChatPipeline:
get_path_service().get_task_workspace("chat", workspace_key) if workspace_key else None
)
exec_dir = task_dir / "exec" if task_dir is not None else None
+ if tool_name in MASTERY_TOOL_NAMES:
+ # The active path id is server-owned; the model never picks which
+ # learner's progress a mastery tool reads or writes.
+ kwargs["_mastery_path_id"] = self._mastery_path_id(context)
if tool_name == "rag":
kwargs.setdefault("mode", "hybrid")
elif tool_name == "load_tools":
@@ -1026,6 +1069,23 @@ class AgenticChatPipeline:
cleaned = "".join(ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in raw)
return cleaned.strip("_") or "direct"
+ @staticmethod
+ def _mastery_active(context: UnifiedContext) -> bool:
+ """Whether this turn runs in mastery-tutor mode (set by the capability)."""
+ return bool(context.metadata.get("mastery_mode"))
+
+ @staticmethod
+ def _mastery_path_id(context: UnifiedContext) -> str:
+ return str(context.metadata.get("mastery_path_id") or "").strip()
+
+ def _mastery_system_note(self, context: UnifiedContext) -> str:
+ if not self._mastery_active(context):
+ return ""
+ override = self._t("mastery.system")
+ if override:
+ return override
+ return _MASTERY_SYSTEM_ZH if self.language == "zh" else _MASTERY_SYSTEM_EN
+
def _kb_system_note(self, context: UnifiedContext) -> str:
kbs = self._selected_kbs(context)
if not kbs:
diff --git a/deeptutor/agents/chat/prompt_blocks.py b/deeptutor/agents/chat/prompt_blocks.py
index 6cb835b40..37f6470a0 100644
--- a/deeptutor/agents/chat/prompt_blocks.py
+++ b/deeptutor/agents/chat/prompt_blocks.py
@@ -38,6 +38,7 @@ class ChatPromptAssembler:
deferred_tools_manifest: str = "",
notebook_manifest: str = "",
workspace_note: str = "",
+ mastery_note: str = "",
include_tool_manifest: bool = True,
) -> str:
blocks = self.blocks(
@@ -47,6 +48,7 @@ class ChatPromptAssembler:
deferred_tools_manifest=deferred_tools_manifest,
notebook_manifest=notebook_manifest,
workspace_note=workspace_note,
+ mastery_note=mastery_note,
include_tool_manifest=include_tool_manifest,
)
joined = "\n\n---\n\n".join(
@@ -63,6 +65,7 @@ class ChatPromptAssembler:
deferred_tools_manifest: str = "",
notebook_manifest: str = "",
workspace_note: str = "",
+ mastery_note: str = "",
include_tool_manifest: bool = True,
) -> list[PromptBlock]:
blocks: list[PromptBlock] = [
@@ -70,6 +73,10 @@ class ChatPromptAssembler:
PromptBlock("runtime_policy", self._t("runtime_policy")),
PromptBlock("loop", self._t("loop.system")),
]
+ # Mastery-tutor playbook sits high so it frames the whole turn when a
+ # mastery path is active; empty (and omitted) for ordinary chat.
+ if mastery_note:
+ blocks.append(PromptBlock("mastery_tutor", mastery_note))
if context.persona_context:
blocks.append(PromptBlock("persona_style", context.persona_context))
if context.memory_context:
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index 7efeafa0d..fa479a654 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -9,6 +9,7 @@ from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from pydantic import ValidationError as PydanticValidationError
+from deeptutor.learning import policy as learning_policy
from deeptutor.learning import prompts as learning_prompts
from deeptutor.learning.models import (
KnowledgePoint,
@@ -115,6 +116,21 @@ async def get_progress(book_id: str):
return progress.model_dump()
[email protected]("/progress/{book_id}/map")
+async def get_progress_map(book_id: str):
+ """The dashboard view of a path: the gate-decided next step plus a map of
+ every objective's status (new / learning / mastered). The per-type gate
+ lives in ``learning.policy`` so the dashboard and the tutor agree."""
+ _validate_book_id(book_id)
+ service = get_learning_service()
+ progress = service.get_or_create(book_id)
+ return {
+ "book_id": book_id,
+ "next": learning_policy.next_objective(progress).to_dict(),
+ "map": learning_policy.map_summary(progress),
+ }
+
+
@router.post("/progress/{book_id}/init-modules")
async def init_modules(book_id: str, body: InitModulesRequest):
_validate_book_id(book_id)
@@ -183,10 +199,12 @@ async def redo_progress(book_id: str):
raise HTTPException(status_code=404, detail="Progress not found")
progress.current_stage = LearningStage.DIAGNOSTIC
progress.mastery_levels = {}
+ progress.qualitative_mastery = {}
progress.quiz_attempts = []
progress.error_records = []
progress.repetition_states = {}
progress.review_queue = []
+ progress.pending_question = None
progress.feynman_retries = {}
progress.feynman_explanations = {}
progress.stage_failure_counts = {}
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 80c4eed13..3da7ef46f 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -24,11 +24,8 @@ Supported client message ``type`` values:
- ``check_active_turn`` — report whether the session has a live running turn;
replies with ``active_turn_info`` (``turn_id``/``status``), marking stale
persisted "running" rows as cancelled when no live execution exists.
-- ``user_input`` — deliver a Mastery Path answer to the turn's StreamBus
- (resolves a pending ``wait_for_input``).
-- ``change_module`` — switch the active Mastery Path module; replies with
- ``module_changed`` (``module_id``/``success``) before cancelling any active
- turn so the frontend processes the switch before the cancellation.
+- ``user_input`` — deliver a learner answer to the turn's StreamBus
+ (resolves a pending ``wait_for_input``, e.g. an ``ask_user`` pause).
"""
from __future__ import annotations
@@ -312,44 +309,6 @@ async def unified_websocket(ws: WebSocket) -> None:
bus.submit_input(str(msg.get("content") or ""))
continue
- if msg_type == "change_module":
- session_id = str(msg.get("session_id") or "").strip()
- module_id = str(msg.get("module_id") or "").strip()
- 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.service import LearningService
- from deeptutor.learning.storage import LearningStore
- from deeptutor.services.session import get_turn_runtime_manager
-
- # Pedagogy (module lookup + reset to the EXPLAIN stage) lives in
- # the service; the router only owns the transport ordering below.
- service = LearningService(LearningStore())
- progress = service.get_or_create(session_id)
- found = service.switch_module(progress, module_id)
-
- # Send module_changed BEFORE cancelling so the frontend
- # processes the module switch before any cancellation error.
- await safe_send(
- {"type": "module_changed", "module_id": module_id, "success": found}
- )
-
- # Cancel any active turn to prevent its finally block from
- # overwriting the module change with stale progress.
- runtime = get_turn_runtime_manager()
- active_turn = await runtime.store.get_active_turn(session_id)
- if active_turn:
- await runtime.cancel_turn(active_turn["id"])
-
- if found:
- service.save(progress)
- continue
-
await safe_send({"type": "error", "content": f"Unknown type: {msg_type}"})
except WebSocketDisconnect:
diff --git a/deeptutor/capabilities/mastery_path.py b/deeptutor/capabilities/mastery_path.py
index da19caa73..229152f42 100644
--- a/deeptutor/capabilities/mastery_path.py
+++ b/deeptutor/capabilities/mastery_path.py
@@ -1,730 +1,76 @@
-"""Mastery Path capability — structured mastery-based learning over a turn stream.
-
-Drives a small state machine inside the agent/turn loop::
-
- diagnostic -> (per knowledge point: explain -> feynman_check)
- -> practice -> error_diagnosis -> review -> completed
-
-Each handler makes at most one LLM call, optionally runs an interactive
-question loop (blocking on the stream for the student's answer), updates the
-persisted ``LearningProgress``, and advances the stage. Grading and mastery
-math live in ``LearningService`` / ``grading`` / ``mastery`` — this file only
-orchestrates the conversation; it owns no pedagogy arithmetic.
+"""Mastery Path capability — mastery-based tutoring driven by the chat loop.
+
+There is no bespoke state machine here anymore. The chat agent loop IS the
+tutor: this capability only marks the turn as mastery mode and resolves the
+active path id, then runs the standard agentic chat pipeline. The pipeline
+mounts the mastery tools (``mastery_status`` / ``mastery_quiz`` /
+``mastery_grade`` / ``mastery_assess`` / ``mastery_build``) and injects the
+tutor playbook; the pure engine in :mod:`deeptutor.learning` owns the hard,
+per-type mastery gate and the spaced-repetition arithmetic.
+
+Design axiom (shared with chat): the intelligence lives at the loop's exit —
+the model decides what to teach and how to question — while the gate that
+decides *whether the learner may advance* is a deterministic engine call.
"""
from __future__ import annotations
-import asyncio
-import json
-import logging
-from typing import Any
+import re
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
-from deeptutor.learning import prompts
-from deeptutor.learning.models import (
- DiagnosticResult,
- ErrorType,
- KnowledgeType,
- LearningProgress,
- LearningStage,
-)
-from deeptutor.learning.scheduler import SpacedRepetitionScheduler
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
-from deeptutor.services.llm import complete
-from deeptutor.utils.json_parser import parse_json_response
+from deeptutor.tools.mastery_tool import MASTERY_TOOL_NAMES
+
+_UNSAFE_ID_CHARS = re.compile(r"[^A-Za-z0-9_-]")
+
+
+def _sanitize_path_id(raw: str) -> str:
+ """Make *raw* a safe storage key (matches ``LearningStore`` path guard)."""
+ cleaned = _UNSAFE_ID_CHARS.sub("_", raw).strip("_")
+ return cleaned or "default"
-from ._i18n import StatusI18n
-logger = logging.getLogger(__name__)
+def resolve_mastery_path_id(context: UnifiedContext) -> str:
+ """Resolve which learner-path the turn operates on.
-# Answer-bearing keys stripped from a question before it is streamed to the
-# client, and read back to grade the student's answer in-turn.
-_ANSWER_KEYS = ("answer", "correct_answer", "explanation", "solution")
-_INPUT_TIMEOUT = 120
+ Prefers an explicit ``mastery_path_id`` set by the frontend (so the tutor
+ and the build wizard / dashboard agree on one storage key), then a book
+ reference, then the session id for an ad-hoc path built inside a chat.
+ """
+ explicit = str(context.metadata.get("mastery_path_id") or "").strip()
+ if explicit:
+ return _sanitize_path_id(explicit)
+ refs = (context.metadata or {}).get("book_references", [])
+ if refs:
+ ref = refs[0]
+ if isinstance(ref, str) and ref.strip():
+ return _sanitize_path_id(ref)
+ if isinstance(ref, dict):
+ candidate = str(ref.get("book_id") or ref.get("id") or "").strip()
+ if candidate:
+ return _sanitize_path_id(candidate)
+ return _sanitize_path_id(str(context.session_id or "default"))
class MasteryPathCapability(BaseCapability):
manifest = CapabilityManifest(
name="mastery_path",
- description="Mastery Path: structured mastery-based learning with spaced repetition",
- # Single source of truth: the stages ARE the LearningStage enum.
- stages=[s.value for s in LearningStage],
- tools_used=[],
+ description=(
+ "Mastery-based tutoring: the chat agent loop drives an adaptive "
+ "mastery path with a hard, per-type mastery gate and spaced review."
+ ),
+ stages=["responding"],
+ tools_used=[*MASTERY_TOOL_NAMES, "rag", "read_source", "ask_user"],
+ cli_aliases=["mastery"],
)
- _FEYNMAN_MAX_RETRIES = 3
- _FEYNMAN_PASS_MASTERY = 0.6
- _LLM_TIMEOUT_SECONDS = 60
- _ERROR_DIAGNOSIS_TIMEOUT_SECONDS = 45
- _STAGE_MAX_FAILURES = 2
- _STAGE_MAX_CUMULATIVE_FAILURES = 4
-
- def __init__(
- self,
- service: LearningService | None = None,
- scheduler: SpacedRepetitionScheduler | None = None,
- store: LearningStore | None = None,
- ) -> None:
- if service is not None:
- self._service = service
- self._store = service._store
- else:
- self._store = store or LearningStore()
- self._service = LearningService(self._store)
- self._scheduler = scheduler or SpacedRepetitionScheduler()
-
- # ── State-machine entry ──────────────────────────────────────────────
-
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
- language = getattr(context, "language", "zh") or "zh"
- status = StatusI18n(self.manifest.name, language)
- self._active_status = status
- localized_prompts = prompts.get_learning_prompts(language)
- progress = self._service.get_or_create(self._resolve_book_id(context))
- stage = progress.current_stage
-
- if stage == LearningStage.COMPLETED:
- async with stream.stage("completed", source=self.manifest.name):
- await stream.content(
- status.t("completed", "学习流程已完成。"), source=self.manifest.name
- )
- return
-
- if not any(mod.knowledge_points for mod in progress.modules):
- async with stream.stage("blocked", source=self.manifest.name):
- await stream.content(
- status.t(
- "blocked_no_modules",
- "请先创建至少一个包含知识点的学习模块,再开始 Mastery Path。",
- ),
- source=self.manifest.name,
- )
- return
-
- handler = self._STAGE_HANDLERS.get(stage)
- if handler is None:
- return
- try:
- await handler(self, progress, stream, localized_prompts, status)
- except Exception as exc:
- logger.error("Stage %s failed: %s", stage, exc, exc_info=True)
- async with stream.stage("error", source=self.manifest.name):
- await stream.content(
- status.t("stage_failed", "阶段执行失败,进度已保存,下次将继续此阶段。"),
- source=self.manifest.name,
- )
- finally:
- self._service.save(progress)
-
- # ── Context / lookup helpers ─────────────────────────────────────────
-
- @staticmethod
- def _resolve_book_id(context: UnifiedContext) -> str:
- book_id = getattr(context, "book_id", None)
- if book_id:
- return book_id
- refs = (getattr(context, "metadata", {}) or {}).get("book_references", [])
- if refs:
- ref = refs[0]
- return ref if isinstance(ref, str) else (ref.get("book_id") or ref.get("id", "default"))
- return getattr(context, "session_id", "default")
-
- def _current_knowledge_points(self, progress: LearningProgress) -> list:
- if not progress.modules:
- return []
- for mod in progress.modules:
- if mod.id == progress.current_module_id:
- return mod.knowledge_points
- return progress.modules[0].knowledge_points
-
- def _current_kp(self, progress: LearningProgress):
- kps = self._current_knowledge_points(progress)
- if kps and progress.current_kp_index < len(kps):
- return kps[progress.current_kp_index]
- return None
-
- @staticmethod
- def _safe_json(text: str, default: dict) -> dict:
- result = parse_json_response(text, fallback=default)
- return result if isinstance(result, dict) else default
-
- @staticmethod
- def _is_passed(value: Any) -> bool:
- return value is True or str(value).lower() in ("true", "1", "yes")
-
- @staticmethod
- def _prompt(localized_prompts: dict[str, Any], path: str, default: str) -> str:
- value: Any = localized_prompts
- for part in path.split("."):
- if not isinstance(value, dict):
- return default
- value = value.get(part)
- return value if isinstance(value, str) and value else default
-
- @staticmethod
- def _default_status() -> StatusI18n:
- return StatusI18n("mastery_path", "zh")
-
- @staticmethod
- def _default_prompts() -> dict[str, Any]:
- return prompts.get_learning_prompts("zh")
-
- # ── LLM call with bounded retry + graceful per-stage skip ────────────
-
- async def _call_llm(
- self,
- system_prompt: str,
- user_message: str,
- progress: LearningProgress,
- stage_name: str,
- stream: StreamBus,
- *,
- status: StatusI18n | None = None,
- timeout: float | None = None,
- ) -> str | None:
- """Call the LLM with bounded retry. Returns ``None`` when the stage is
- skipped — either it already failed too many times across turns, or
- every retry this turn failed — so the caller can degrade gracefully
- instead of wedging the state machine on a flaky model."""
- status = (
- status or getattr(self, "_active_status", None) or StatusI18n(self.manifest.name, "zh")
- )
- if progress.stage_failure_counts.get(stage_name, 0) >= self._STAGE_MAX_CUMULATIVE_FAILURES:
- await stream.content(
- status.t(
- "stage_skipped", "阶段 {stage_name} 已多次失败,跳过。", stage_name=stage_name
- ),
- source=self.manifest.name,
- metadata={"type": "stage_skipped", "stage": stage_name},
- )
- return None
- for attempt in range(self._STAGE_MAX_FAILURES):
- try:
- response = await asyncio.wait_for(
- complete(prompt=user_message, system_prompt=system_prompt),
- timeout=timeout or self._LLM_TIMEOUT_SECONDS,
- )
- progress.stage_failure_counts.pop(stage_name, None)
- progress.stage_failure_notes.pop(stage_name, None)
- return response
- except Exception as exc:
- progress.stage_failure_counts[stage_name] = (
- progress.stage_failure_counts.get(stage_name, 0) + 1
- )
- progress.stage_failure_notes[stage_name] = str(exc)
- if attempt < self._STAGE_MAX_FAILURES - 1:
- continue
- await stream.content(
- status.t(
- "stage_degraded",
- "阶段 {stage_name} 暂时不可用,已记录并跳过。",
- stage_name=stage_name,
- ),
- source=self.manifest.name,
- metadata={"type": "stage_degraded", "stage": stage_name},
- )
- return None
-
- # ── Question helpers ─────────────────────────────────────────────────
-
- @staticmethod
- def _question_id(item: Any, prefix: str, index: int) -> str:
- if isinstance(item, dict):
- return str(item.get("question_id") or item.get("id") or f"{prefix}_{index}")
- return f"{prefix}_{index}"
-
- @classmethod
- def _extract_answers(cls, data: dict, prefix: str) -> dict[str, str]:
- """Map question_id -> expected answer, accepting either a parallel
- ``answers`` array or inline answer keys on each question."""
- items = data.get("questions") or data.get("exercises") or []
- parallel = data.get("answers", [])
- answers: dict[str, str] = {}
- for i, item in enumerate(items):
- qid = cls._question_id(item, prefix, i)
- if isinstance(item, dict):
- for key in _ANSWER_KEYS:
- if key in item:
- answers[qid] = str(item[key])
- break
- if qid not in answers and i < len(parallel):
- answers[qid] = str(parallel[i])
- return answers
-
- @staticmethod
- def _strip_answer(question: Any) -> Any:
- if not isinstance(question, dict):
- return question
- return {k: v for k, v in question.items() if k not in _ANSWER_KEYS}
-
- @classmethod
- def _attribute_kps(cls, data: dict, kps: list, prefix: str) -> dict[str, str]:
- """Map question_id -> knowledge_point_id from LLM-supplied labels,
- distributing un-attributed questions round-robin across module KPs
- instead of biasing every question toward the first."""
-
- def norm(value: Any) -> str:
- return str(value or "").strip().lower()
-
- label_to_id: dict[str, str] = {}
- for kp in kps:
- label_to_id[norm(kp.id)] = kp.id
- label_to_id[norm(kp.name)] = kp.id
- items = data.get("questions") or data.get("exercises") or []
- result: dict[str, str] = {}
- for i, item in enumerate(items):
- qid = cls._question_id(item, prefix, i)
- resolved = ""
- if isinstance(item, dict):
- raw = (
- item.get("knowledge_point_id")
- or item.get("knowledge_point")
- or item.get("knowledge_point_name")
- or item.get("kp_id")
- or item.get("kp")
- or ""
- )
- resolved = label_to_id.get(norm(raw), "")
- if not resolved and kps:
- resolved = kps[i % len(kps)].id
- result[qid] = resolved
- return result
-
- async def _run_quiz(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- data: dict,
- *,
- prefix: str,
- attribute_kps: bool,
- status: StatusI18n | None = None,
- ) -> tuple[int, int]:
- """Stream each question (answers stripped), block for the student's
- answer, and grade it via ``LearningService.grade_and_record``. Returns
- ``(correct_count, total)``. Answers are kept in memory for the turn —
- nothing is persisted server-side because grading happens in-turn."""
- items = data.get("questions") or data.get("exercises") or []
- status = status or self._default_status()
- answers = self._extract_answers(data, prefix)
- kps = self._current_knowledge_points(progress)
- kp_map = self._attribute_kps(data, kps, prefix) if attribute_kps else {}
- default_kp = kps[0].id if (attribute_kps and kps) else ""
- correct = 0
- for i, item in enumerate(items):
- qid = self._question_id(item, prefix, i)
- await stream.content(
- json.dumps(
- {"question": self._strip_answer(item), "question_id": qid}, ensure_ascii=False
- ),
- source=self.manifest.name,
- )
- user_answer = await stream.wait_for_input(
- status.t("answer_prompt", "请回答"),
- source=self.manifest.name,
- timeout=_INPUT_TIMEOUT,
- )
- if self._service.grade_and_record(
- progress,
- question_id=qid,
- knowledge_point_id=kp_map.get(qid, "") or default_kp,
- module_id=progress.current_module_id or "",
- user_answer=user_answer,
- expected_answer=answers.get(qid, ""),
- scheduler=self._scheduler,
- ):
- correct += 1
- return correct, len(items)
-
- # ── Stage handlers ───────────────────────────────────────────────────
-
- async def _run_diagnostic(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("diagnostic", source=self.manifest.name):
- await stream.content(
- status.t("diagnostic_generating", "正在生成诊断题..."), source=self.manifest.name
- )
- response = await self._call_llm(
- self._prompt(localized_prompts, "diagnostic.system", prompts.DIAGNOSTIC_SYSTEM),
- self._prompt(localized_prompts, "diagnostic.user", prompts.DIAGNOSTIC_USER),
- progress,
- "diagnostic",
- stream,
- )
- if response is None:
- progress.diagnostic = DiagnosticResult()
- else:
- data = self._safe_json(response, {"questions": [], "answers": []})
- correct, total = await self._run_quiz(
- progress,
- stream,
- data,
- prefix="diag",
- attribute_kps=False,
- status=status,
- )
- progress.diagnostic = DiagnosticResult(total_questions=total, correct_count=correct)
- self._service.advance_stage(progress, LearningStage.EXPLAIN)
-
- async def _run_explain(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("explain", source=self.manifest.name):
- kp = self._current_kp(progress)
- default_kp = status.t("current_knowledge_point", "当前知识点")
- await stream.content(
- status.t("explain_generating", "正在生成讲解内容..."), source=self.manifest.name
- )
- response = await self._call_llm(
- self._prompt(localized_prompts, "explain.system", prompts.EXPLAIN_SYSTEM),
- self._prompt(localized_prompts, "explain.user", prompts.EXPLAIN_USER).format(
- knowledge_point=kp.name if kp else default_kp
- ),
- progress,
- "explain",
- stream,
- )
- if response is None:
- self._advance_after_kp(progress)
- return
- await stream.content(response, source=self.manifest.name)
- self._service.advance_stage(progress, LearningStage.FEYNMAN_CHECK)
-
- async def _run_feynman_check(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("feynman_check", source=self.manifest.name):
- kp = self._current_kp(progress)
- kp_name = kp.name if kp else status.t("current_knowledge_point", "当前知识点")
- kp_id = kp.id if kp else ""
-
- await stream.content(
- status.t(
- "feynman_instruction",
- '请用自己的话解释"{kp_name}",就像教一个高中生一样。',
- kp_name=kp_name,
- ),
- source=self.manifest.name,
- )
- explanation = await stream.wait_for_input(
- status.t("feynman_input_prompt", "请输入你的解释"),
- source=self.manifest.name,
- timeout=_INPUT_TIMEOUT,
- )
- if not explanation.strip():
- self._advance_after_kp(progress)
- return
-
- await stream.content(
- status.t("feynman_evaluating", "正在评估你的解释..."), source=self.manifest.name
- )
- response = await self._call_llm(
- self._prompt(localized_prompts, "feynman.system", prompts.FEYNMAN_SYSTEM),
- self._prompt(localized_prompts, "feynman.user", prompts.FEYNMAN_USER).format(
- knowledge_point=kp_name
- )
- + "\n"
- + status.t(
- "student_explanation_label",
- "学生解释:{explanation}",
- explanation=explanation,
- ),
- progress,
- "feynman_check",
- stream,
- )
- if response is None:
- if kp_id:
- progress.feynman_explanations[kp_id] = explanation
- result = {
- "passed": False,
- "feedback": status.t(
- "feynman_unavailable_feedback",
- "未评估(评估服务暂时不可用)",
- ),
- "gap": "",
- }
- else:
- result = self._safe_json(response, {"passed": False, "feedback": "", "gap": ""})
-
- await stream.content(json.dumps(result, ensure_ascii=False), source=self.manifest.name)
- if self._is_passed(result.get("passed")):
- progress.feynman_retries[kp_id] = 0
- progress.feynman_explanations.pop(kp_id, None)
- if kp_id:
- progress.mastery_levels[kp_id] = max(
- progress.mastery_levels.get(kp_id, 0.0), self._FEYNMAN_PASS_MASTERY
- )
- self._advance_after_kp(progress)
- return
-
- retries = progress.feynman_retries.get(kp_id, 0) + 1
- progress.feynman_retries[kp_id] = retries
- if retries >= self._FEYNMAN_MAX_RETRIES:
- if kp_id:
- progress.mastery_levels[kp_id] = 0.0
- await stream.content(
- status.t(
- "feynman_weak_skipped",
- "该知识点已尝试 {retries} 次,标记为薄弱并跳过。",
- retries=retries,
- ),
- source=self.manifest.name,
- )
- self._advance_after_kp(progress)
- else:
- await stream.content(
- status.t(
- "feynman_retry_feedback",
- "反馈:{feedback}(第 {retries}/{max_retries} 次重试)",
- feedback=result.get(
- "feedback",
- status.t("feynman_retry_default", "请重新学习"),
- ),
- retries=retries,
- max_retries=self._FEYNMAN_MAX_RETRIES,
- ),
- source=self.manifest.name,
- )
- self._service.advance_stage(progress, LearningStage.EXPLAIN)
-
- async def _run_practice(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("practice", source=self.manifest.name):
- kps = self._current_knowledge_points(progress)
- await stream.content(
- status.t("practice_generating", "正在生成练习题..."), source=self.manifest.name
- )
- response = await self._call_llm(
- self._prompt(localized_prompts, "practice.system", prompts.PRACTICE_SYSTEM),
- self._prompt(localized_prompts, "practice.user", prompts.PRACTICE_USER).format(
- knowledge_points=", ".join(kp.name for kp in kps)
- ),
- progress,
- "practice",
- stream,
- )
- if response is None:
- self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)
- return
- data = self._safe_json(response, {"questions": []})
- prefix = (
- f"{progress.current_module_id}_practice"
- if progress.current_module_id
- else "practice"
- )
- correct, total = await self._run_quiz(
- progress,
- stream,
- data,
- prefix=prefix,
- attribute_kps=True,
- status=status,
- )
- if total:
- pct = correct / total * 100
- tail = (
- status.t("practice_tail_good", " 表现不错,继续加油!")
- if pct >= 70
- else status.t("practice_tail_review", " 建议回顾相关知识点。")
- )
- await stream.content(
- status.t(
- "practice_complete",
- "练习完成!正确 {correct}/{total} 题({pct:.0f}%)。{tail}",
- correct=correct,
- total=total,
- pct=pct,
- tail=tail,
- ),
- source=self.manifest.name,
- )
- self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)
-
- async def _run_error_diagnosis(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("error_diagnosis", source=self.manifest.name):
- active = [r for r in progress.error_records if r.status in ("active", "retrying")]
- if not active:
- await stream.content(
- status.t("no_errors_skip", "没有待诊断的错题,跳过。"),
- source=self.manifest.name,
- )
- self._service.advance_stage(progress, LearningStage.REVIEW)
- return
- await stream.content(
- status.t("error_diagnosis_generating", "正在生成错误诊断..."),
- source=self.manifest.name,
- )
- error_context = json.dumps(
- [
- {
- "question_id": r.question_id,
- "error_type": r.error_type.value if r.error_type else "",
- "self_attribution": r.self_attribution,
- }
- for r in active
- ],
- ensure_ascii=False,
- )
- response = await self._call_llm(
- self._prompt(
- localized_prompts,
- "error_diagnosis.system",
- prompts.ERROR_DIAGNOSIS_SYSTEM,
- ),
- self._prompt(
- localized_prompts,
- "error_diagnosis.user",
- prompts.ERROR_DIAGNOSIS_USER,
- )
- + f"\n{status.t('error_context_label', '错题记录')}:{error_context}",
- progress,
- "error_diagnosis",
- stream,
- timeout=self._ERROR_DIAGNOSIS_TIMEOUT_SECONDS,
- )
- if response is None:
- for rec in active:
- rec.ai_confirmation = status.t(
- "error_diagnosis_unavailable",
- "error_diagnosis_unavailable",
- )
- self._service.advance_stage(progress, LearningStage.REVIEW)
- return
- data = self._safe_json(response, {"diagnoses": []})
- by_qid = {r.question_id: r for r in active}
- for diag in data.get("diagnoses", []):
- rec = by_qid.get(diag.get("question_id", ""))
- if rec is None:
- continue
- new_type = diag.get("error_type", "")
- if new_type:
- try:
- rec.error_type = ErrorType(new_type)
- except (ValueError, KeyError):
- pass
- rec.ai_confirmation = diag.get("ai_confirmation", "")
- await stream.content(response, source=self.manifest.name)
- self._service.advance_stage(progress, LearningStage.REVIEW)
-
- async def _run_review(
- self,
- progress: LearningProgress,
- stream: StreamBus,
- localized_prompts: dict[str, Any] | None = None,
- status: StatusI18n | None = None,
- ) -> None:
- localized_prompts = localized_prompts or self._default_prompts()
- status = status or self._default_status()
- self._active_status = status
- async with stream.stage("review", source=self.manifest.name):
- self._init_repetition_states(progress)
- progress.review_queue = self._scheduler.build_review_queue(progress)
- await stream.content(
- status.t("review_generating", "正在生成复习内容..."), source=self.manifest.name
- )
- response = await self._call_llm(
- self._prompt(localized_prompts, "review.system", prompts.REVIEW_SYSTEM),
- self._prompt(localized_prompts, "review.user", prompts.REVIEW_USER),
- progress,
- "review",
- stream,
- )
- await stream.content(
- response
- or status.t(
- "review_fallback",
- "请回顾之前的学习内容,重点复习薄弱知识点。",
- ),
- source=self.manifest.name,
- )
- if self._advance_to_next_module(progress):
- self._service.advance_stage(progress, LearningStage.EXPLAIN)
- else:
- self._service.advance_stage(progress, LearningStage.COMPLETED)
-
- # ── Loop topology ────────────────────────────────────────────────────
-
- def _advance_after_kp(self, progress: LearningProgress) -> None:
- """Move to the next knowledge point's EXPLAIN, or to PRACTICE once the
- current module's knowledge points are exhausted."""
- kps = self._current_knowledge_points(progress)
- if progress.current_kp_index + 1 < len(kps):
- progress.current_kp_index += 1
- self._service.advance_stage(progress, LearningStage.EXPLAIN)
- else:
- self._service.advance_stage(progress, LearningStage.PRACTICE)
-
- def _advance_to_next_module(self, progress: LearningProgress) -> bool:
- ids = [m.id for m in progress.modules]
- if not progress.current_module_id or progress.current_module_id not in ids:
- return False
- idx = ids.index(progress.current_module_id)
- if idx + 1 < len(ids):
- progress.current_module_id = ids[idx + 1]
- progress.current_kp_index = 0
- return True
- return False
-
- def _init_repetition_states(self, progress: LearningProgress) -> None:
- for mod in progress.modules:
- if mod.id != progress.current_module_id:
- continue
- for kp in mod.knowledge_points:
- if kp.id not in progress.repetition_states:
- kp_type = progress.knowledge_types.get(kp.id, KnowledgeType.MEMORY)
- progress.repetition_states[kp.id] = self._scheduler.get_initial_state(kp_type)
-
- _STAGE_HANDLERS = {
- LearningStage.DIAGNOSTIC: _run_diagnostic,
- LearningStage.EXPLAIN: _run_explain,
- LearningStage.FEYNMAN_CHECK: _run_feynman_check,
- LearningStage.PRACTICE: _run_practice,
- LearningStage.ERROR_DIAGNOSIS: _run_error_diagnosis,
- LearningStage.REVIEW: _run_review,
- }
+ context.metadata["mastery_mode"] = True
+ context.metadata["mastery_path_id"] = resolve_mastery_path_id(context)
+ pipeline = AgenticChatPipeline(language=context.language)
+ await pipeline.run(context, stream)
-__all__ = ["MasteryPathCapability"]
+__all__ = ["MasteryPathCapability", "resolve_mastery_path_id"]
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index 2633354df..ed5c0af6e 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -161,6 +161,27 @@ class ReviewTask(BaseModel):
state: RepetitionState
+class PendingQuestion(BaseModel):
+ """A question posed to the learner and awaiting their answer.
+
+ Persisted so grading is deterministic across turns: the expected answer
+ lives here server-side and never round-trips through the model. The tutor
+ poses a question with ``mastery_quiz`` (storing this), the learner answers
+ on a later turn, and ``mastery_grade`` scores the stored answer.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ question_id: str
+ knowledge_point_id: str
+ module_id: str = ""
+ prompt: str = ""
+ question_type: str = "short"
+ expected_answer: str = ""
+ options: list[str] = Field(default_factory=list)
+ created_at: float = Field(default_factory=time.time)
+
+
class LearningProgress(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -171,11 +192,18 @@ class LearningProgress(BaseModel):
current_stage: LearningStage = LearningStage.DIAGNOSTIC
current_kp_index: int = 0
mastery_levels: dict[str, float] = Field(default_factory=dict)
+ # Qualitative gate for CONCEPT / DESIGN knowledge points: True once the
+ # tutor judges the learner's explanation sufficient (``mastery_assess``).
+ # The quantitative ``mastery_levels`` gate covers MEMORY / PROCEDURE.
+ qualitative_mastery: dict[str, bool] = Field(default_factory=dict)
knowledge_types: dict[str, KnowledgeType] = Field(default_factory=dict)
quiz_attempts: list[QuizAttempt] = Field(default_factory=list)
error_records: list[ErrorRecord] = Field(default_factory=list)
repetition_states: dict[str, RepetitionState] = Field(default_factory=dict)
review_queue: list[ReviewTask] = Field(default_factory=list)
+ # A single outstanding question; grading reads its expected answer so the
+ # model never has to recall it across turns.
+ pending_question: PendingQuestion | None = None
feynman_retries: dict[str, int] = Field(default_factory=dict)
feynman_explanations: dict[str, str] = Field(default_factory=dict)
stage_failure_counts: dict[str, int] = Field(default_factory=dict)
@@ -197,5 +225,6 @@ __all__ = [
"ErrorRecord",
"RepetitionState",
"ReviewTask",
+ "PendingQuestion",
"LearningProgress",
]
diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.py
new file mode 100644
index 000000000..b481b7479
--- /dev/null
+++ b/deeptutor/learning/policy.py
@@ -0,0 +1,289 @@
+"""Mastery Path policy — pure decisions over a :class:`LearningProgress`.
+
+No LLM calls, no I/O. This is the engine the chat-loop tutor consults each
+turn. It answers three questions:
+
+* **is this objective mastered?** (:func:`is_mastered` — a HARD, per-type gate)
+* **what should the learner work on next?** (:func:`next_objective`)
+* **what does the whole map look like?** (:func:`map_summary`)
+
+The gate is the heart of mastery-based learning. An objective only counts as
+mastered when the evidence clears its threshold, and :func:`next_objective`
+keeps returning the same objective until it does — advancement is *computed
+from what is mastered*, never tracked by a stage counter. Objective ordering
+follows module order then knowledge-point order; an objective the learner has
+already proven is skipped (the "test out" / compression path) because the gate
+reads proven mastery, not a fixed sequence of stages.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import time
+
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningProgress,
+ ReviewTask,
+)
+
+# Quantitative gate for objective knowledge types: the learner must reach this
+# mastery (recency-weighted accuracy; see ``mastery.compute_mastery``) before
+# the objective unlocks. ~0.9 mirrors Alpha School's "90% before you advance".
+QUANTITATIVE_GATE: dict[KnowledgeType, float] = {
+ KnowledgeType.MEMORY: 0.9,
+ KnowledgeType.PROCEDURE: 0.9,
+}
+
+# CONCEPT / DESIGN are gated qualitatively — a Feynman-style explanation judged
+# by the tutor via ``mastery_assess`` — rather than by string-graded accuracy,
+# because there is rarely a single canonical right answer to match against.
+QUALITATIVE_TYPES: frozenset[KnowledgeType] = frozenset(
+ {KnowledgeType.CONCEPT, KnowledgeType.DESIGN}
+)
+
+# Display mastery a qualitative pass maps to, so the map's colours agree with
+# the gate even though qualitative mastery is a boolean, not a score. (The
+# fail-side display is handled in ``LearningService.record_qualitative``.)
+_QUALITATIVE_PASS_DISPLAY = 1.0
+
+
+def gate_threshold(kp_type: KnowledgeType) -> float:
+ """The quantitative mastery bar for *kp_type* (qualitative types report
+ their pass-display value so callers have a single number to show)."""
+ if kp_type in QUALITATIVE_TYPES:
+ return _QUALITATIVE_PASS_DISPLAY
+ return QUANTITATIVE_GATE.get(kp_type, 0.9)
+
+
+def is_mastered(progress: LearningProgress, kp: KnowledgePoint) -> bool:
+ """Whether ``kp`` clears its mastery gate.
+
+ * MEMORY / PROCEDURE: recency-weighted accuracy ≥ the type's threshold.
+ * CONCEPT / DESIGN: a recorded qualitative pass (``mastery_assess``).
+ """
+ if kp.type in QUALITATIVE_TYPES:
+ return bool(progress.qualitative_mastery.get(kp.id, False))
+ return progress.mastery_levels.get(kp.id, 0.0) >= gate_threshold(kp.type)
+
+
+def display_mastery(progress: LearningProgress, kp: KnowledgePoint) -> float:
+ """A 0..1 number for the map UI. Qualitatively-mastered points show full;
+ otherwise the recency-weighted accuracy stands in."""
+ if kp.type in QUALITATIVE_TYPES and progress.qualitative_mastery.get(kp.id):
+ return _QUALITATIVE_PASS_DISPLAY
+ return float(progress.mastery_levels.get(kp.id, 0.0))
+
+
+def objective_status(progress: LearningProgress, kp: KnowledgePoint) -> str:
+ """``"mastered"`` | ``"learning"`` | ``"new"`` for one knowledge point."""
+ if is_mastered(progress, kp):
+ return "mastered"
+ seen = any(a.knowledge_point_id == kp.id for a in progress.quiz_attempts) or (
+ kp.id in progress.qualitative_mastery
+ )
+ return "learning" if seen else "new"
+
+
+def due_reviews(progress: LearningProgress, *, now: float | None = None) -> list[ReviewTask]:
+ """Spaced-repetition tasks whose ``due_at`` has passed, highest priority
+ first. Pure read over ``progress.review_queue`` (built by the scheduler)."""
+ moment = time.time() if now is None else now
+ due = [task for task in progress.review_queue if task.due_at <= moment]
+ due.sort(key=lambda task: task.priority)
+ return due
+
+
+@dataclass(frozen=True)
+class NextStep:
+ """What the tutor should do next, decided by the gate — not a stage cursor.
+
+ ``action`` is advisory for the model's pedagogy; the binding fact is the
+ objective and whether it is mastered. Values:
+
+ * ``answer_pending`` — a posed question awaits the learner's answer.
+ * ``review`` — a spaced-repetition item is due.
+ * ``probe`` — an untouched objective; test out before teaching.
+ * ``practice`` — a quantitative objective below its gate.
+ * ``assess`` — a qualitative objective awaiting a Feynman-style check.
+ * ``complete`` — every objective mastered, nothing due.
+ """
+
+ action: str
+ module_id: str = ""
+ module_name: str = ""
+ knowledge_point_id: str = ""
+ knowledge_point_name: str = ""
+ knowledge_point_type: str = ""
+ status: str = ""
+ gate: str = ""
+ mastery: float = 0.0
+ threshold: float = 0.0
+ reason: str = ""
+ pending_prompt: str = ""
+
+ def to_dict(self) -> dict:
+ return {
+ "action": self.action,
+ "module_id": self.module_id,
+ "module_name": self.module_name,
+ "knowledge_point_id": self.knowledge_point_id,
+ "knowledge_point_name": self.knowledge_point_name,
+ "knowledge_point_type": self.knowledge_point_type,
+ "status": self.status,
+ "gate": self.gate,
+ "mastery": round(self.mastery, 3),
+ "threshold": round(self.threshold, 3),
+ "reason": self.reason,
+ "pending_prompt": self.pending_prompt,
+ }
+
+
+def find_knowledge_point(
+ progress: LearningProgress, kp_id: str
+) -> tuple[KnowledgePoint | None, str, str]:
+ """Return ``(kp, module_id, module_name)`` for *kp_id*, or ``(None, "", "")``."""
+ for module in progress.modules:
+ for kp in module.knowledge_points:
+ if kp.id == kp_id:
+ return kp, module.id, module.name
+ return None, "", ""
+
+
+def _gate_kind(kp: KnowledgePoint) -> str:
+ return "qualitative" if kp.type in QUALITATIVE_TYPES else "quantitative"
+
+
+def next_objective(progress: LearningProgress, *, now: float | None = None) -> NextStep:
+ """Decide the next thing to work on. Order of precedence:
+
+ 1. an outstanding posed question (grade it before moving on);
+ 2. a due spaced-repetition review (don't let mastered ground decay);
+ 3. the first not-yet-mastered objective in module/KP order (the gate IS
+ the cursor — mastered objectives are skipped);
+ 4. otherwise the path is complete.
+ """
+ pending = progress.pending_question
+ if pending is not None:
+ kp, module_id, module_name = find_knowledge_point(progress, pending.knowledge_point_id)
+ return NextStep(
+ action="answer_pending",
+ module_id=module_id or pending.module_id,
+ module_name=module_name,
+ knowledge_point_id=pending.knowledge_point_id,
+ knowledge_point_name=kp.name if kp else "",
+ knowledge_point_type=kp.type.value if kp else "",
+ status=objective_status(progress, kp) if kp else "learning",
+ gate=_gate_kind(kp) if kp else "",
+ mastery=display_mastery(progress, kp) if kp else 0.0,
+ threshold=gate_threshold(kp.type) if kp else 0.0,
+ reason="A posed question is awaiting the learner's answer; grade it with mastery_grade.",
+ pending_prompt=pending.prompt,
+ )
+
+ due = due_reviews(progress, now=now)
+ if due:
+ kp, module_id, module_name = find_knowledge_point(progress, due[0].knowledge_point_id)
+ if kp is not None:
+ return NextStep(
+ action="review",
+ module_id=module_id,
+ module_name=module_name,
+ knowledge_point_id=kp.id,
+ knowledge_point_name=kp.name,
+ knowledge_point_type=kp.type.value,
+ status=objective_status(progress, kp),
+ gate=_gate_kind(kp),
+ mastery=display_mastery(progress, kp),
+ threshold=gate_threshold(kp.type),
+ reason="This objective is due for spaced-repetition review.",
+ )
+
+ for module in sorted(progress.modules, key=lambda m: m.order):
+ for kp in module.knowledge_points:
+ if is_mastered(progress, kp):
+ continue
+ status = objective_status(progress, kp)
+ gate = _gate_kind(kp)
+ if status == "new":
+ action = "probe"
+ elif gate == "qualitative":
+ action = "assess"
+ else:
+ action = "practice"
+ return NextStep(
+ action=action,
+ module_id=module.id,
+ module_name=module.name,
+ knowledge_point_id=kp.id,
+ knowledge_point_name=kp.name,
+ knowledge_point_type=kp.type.value,
+ status=status,
+ gate=gate,
+ mastery=display_mastery(progress, kp),
+ threshold=gate_threshold(kp.type),
+ reason=(
+ "Untouched objective — probe first to let the learner test out."
+ if status == "new"
+ else "Objective is below its mastery gate; keep working it until it clears."
+ ),
+ )
+
+ return NextStep(action="complete", reason="All objectives are mastered and no reviews are due.")
+
+
+def map_summary(progress: LearningProgress, *, now: float | None = None) -> dict:
+ """A compact, render-ready snapshot of the whole path for the tutor's
+ ``mastery_status`` tool and the dashboard."""
+ counts = {"mastered": 0, "learning": 0, "new": 0, "total": 0}
+ modules_out: list[dict] = []
+ for module in sorted(progress.modules, key=lambda m: m.order):
+ kps_out: list[dict] = []
+ mastered = 0
+ for kp in module.knowledge_points:
+ status = objective_status(progress, kp)
+ counts[status] += 1
+ counts["total"] += 1
+ if status == "mastered":
+ mastered += 1
+ kps_out.append(
+ {
+ "id": kp.id,
+ "name": kp.name,
+ "type": kp.type.value,
+ "status": status,
+ "mastery": round(display_mastery(progress, kp), 3),
+ }
+ )
+ modules_out.append(
+ {
+ "id": module.id,
+ "name": module.name,
+ "order": module.order,
+ "mastered": mastered,
+ "total": len(module.knowledge_points),
+ "knowledge_points": kps_out,
+ }
+ )
+ return {
+ "counts": counts,
+ "due_reviews": len(due_reviews(progress, now=now)),
+ "complete": counts["total"] > 0 and counts["mastered"] == counts["total"],
+ "modules": modules_out,
+ }
+
+
+__all__ = [
+ "QUANTITATIVE_GATE",
+ "QUALITATIVE_TYPES",
+ "NextStep",
+ "gate_threshold",
+ "is_mastered",
+ "display_mastery",
+ "objective_status",
+ "due_reviews",
+ "find_knowledge_point",
+ "next_objective",
+ "map_summary",
+]
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index a26d3ddd0..331f6fb10 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -12,6 +12,7 @@ from deeptutor.learning.models import (
LearningModule,
LearningProgress,
LearningStage,
+ PendingQuestion,
QuizAttempt,
RetryAttempt,
)
@@ -208,6 +209,41 @@ class LearningService:
self.save(progress)
return is_correct
+ # ── Loop-driven tutoring helpers ─────────────────────────────────────
+
+ def set_pending_question(self, progress: LearningProgress, pending: PendingQuestion) -> None:
+ """Store the question the tutor just posed so its expected answer can
+ be graded deterministically on a later turn (never via the model)."""
+ progress.pending_question = pending
+ progress.updated_at = time.time()
+ self.save(progress)
+
+ def clear_pending_question(self, progress: LearningProgress) -> None:
+ progress.pending_question = None
+ progress.updated_at = time.time()
+ self.save(progress)
+
+ def record_qualitative(
+ self,
+ progress: LearningProgress,
+ kp_id: str,
+ *,
+ passed: bool,
+ evidence: str = "",
+ ) -> None:
+ """Record the qualitative (CONCEPT / DESIGN) gate outcome.
+
+ The boolean is the gate of record; ``mastery_levels`` is nudged only so
+ the map's colour matches the gate (full on pass, capped on fail).
+ """
+ progress.qualitative_mastery[kp_id] = bool(passed)
+ current = progress.mastery_levels.get(kp_id, 0.0)
+ progress.mastery_levels[kp_id] = max(current, 1.0) if passed else min(current, 0.4)
+ if evidence:
+ progress.feynman_explanations[kp_id] = evidence
+ progress.updated_at = time.time()
+ self.save(progress)
+
def list_progress(self) -> dict:
"""Return summary of all book progress with per-book error info."""
logger = logging.getLogger(__name__)
diff --git a/deeptutor/learning/tests/test_e2e_flow.py b/deeptutor/learning/tests/test_e2e_flow.py
deleted file mode 100644
index 0d7335f9d..000000000
--- a/deeptutor/learning/tests/test_e2e_flow.py
+++ /dev/null
@@ -1,351 +0,0 @@
-"""End-to-end Mastery Path flow test.
-
-Walks one module / one knowledge point through the full state machine the
-``MasteryPathCapability`` drives:
-
- DIAGNOSTIC -> EXPLAIN -> FEYNMAN_CHECK -> PRACTICE
- -> ERROR_DIAGNOSIS -> REVIEW -> COMPLETED
-
-The LLM is mocked at the handler level (``cap._call_llm``) so each stage gets a
-canned response in call order; grading/mastery/scheduling run for real through
-``LearningService``.
-"""
-
-from contextlib import asynccontextmanager
-import json
-from unittest.mock import AsyncMock
-
-import pytest
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import (
- KnowledgePoint,
- KnowledgeType,
- LearningModule,
- LearningProgress,
- LearningStage,
-)
-from deeptutor.learning.scheduler import SpacedRepetitionScheduler
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
-
-
-class FakeStream:
- """Minimal StreamBus stand-in: records stage/content events and replays a
- queued list of student inputs for ``wait_for_input``."""
-
- def __init__(self) -> None:
- self.events: list[tuple[str, str]] = []
- self.inputs: list[str] = []
- self._input_idx = 0
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(("stage", name))
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(("content", text))
-
- async def wait_for_input(self, prompt, source="", timeout=None):
- if self._input_idx < len(self.inputs):
- val = self.inputs[self._input_idx]
- self._input_idx += 1
- return val
- return ""
-
-
-def _make_cap(tmp_path):
- """Build a capability wired to a real service/store/scheduler over tmp_path."""
- store = LearningStore(root=tmp_path)
- service = LearningService(store)
- scheduler = SpacedRepetitionScheduler()
- cap = MasteryPathCapability(service=service, scheduler=scheduler, store=store)
- return cap, service, store
-
-
-def _single_kp_progress() -> LearningProgress:
- kp = KnowledgePoint(id="kp1", name="Photosynthesis", type=KnowledgeType.CONCEPT, module_id="m1")
- mod = LearningModule(id="m1", name="Biology", order=0, knowledge_points=[kp])
- progress = LearningProgress(book_id="e2e_book")
- progress.modules = [mod]
- progress.current_module_id = "m1"
- progress.current_kp_index = 0
- progress.current_stage = LearningStage.DIAGNOSTIC
- progress.knowledge_types["kp1"] = KnowledgeType.CONCEPT
- return progress
-
-
-async def test_e2e_diagnostic_to_completed(tmp_path):
- """Full happy-path flow from DIAGNOSTIC through COMPLETED, 1 module / 1 KP."""
- cap, service, _store = _make_cap(tmp_path)
- progress = _single_kp_progress()
- stream = FakeStream()
-
- # Canned LLM responses, in stage-handler call order.
- diag_data = json.dumps(
- {
- "questions": [
- {
- "id": "dq1",
- "question": "What is photosynthesis?",
- "answer": "photosynthesis",
- "type": "short",
- }
- ],
- }
- )
- practice_data = json.dumps(
- {
- "questions": [
- {
- "id": "pq1",
- "question": "Define photosynthesis.",
- "answer": "photosynthesis",
- "type": "short",
- "knowledge_point_id": "kp1",
- }
- ],
- }
- )
-
- cap._call_llm = AsyncMock(
- side_effect=[
- diag_data, # 1. DIAGNOSTIC quiz
- "Explain content", # 2. EXPLAIN
- json.dumps({"passed": True, "feedback": "good", "gap": ""}), # 3. FEYNMAN_CHECK judge
- practice_data, # 4. PRACTICE quiz
- "Review content", # 5. REVIEW
- ]
- )
-
- # Student inputs: diagnostic answer, feynman explanation, practice answer.
- stream.inputs = [
- "photosynthesis", # diagnostic question
- "Plants convert sunlight to energy", # feynman explanation
- "photosynthesis", # practice question
- ]
-
- # DIAGNOSTIC -> EXPLAIN
- assert progress.current_stage == LearningStage.DIAGNOSTIC
- await cap._run_diagnostic(progress, stream)
- assert progress.current_stage == LearningStage.EXPLAIN
- assert progress.diagnostic is not None
- assert progress.diagnostic.total_questions == 1
- assert progress.diagnostic.correct_count == 1
-
- # EXPLAIN -> FEYNMAN_CHECK
- await cap._run_explain(progress, stream)
- assert progress.current_stage == LearningStage.FEYNMAN_CHECK
-
- # FEYNMAN_CHECK -> PRACTICE (single KP, passed=True -> _advance_after_kp -> PRACTICE)
- await cap._run_feynman_check(progress, stream)
- assert progress.current_stage == LearningStage.PRACTICE
- # Passing Feynman seeds mastery at the pass floor.
- assert progress.mastery_levels["kp1"] == pytest.approx(
- MasteryPathCapability._FEYNMAN_PASS_MASTERY
- )
-
- # PRACTICE -> ERROR_DIAGNOSIS
- await cap._run_practice(progress, stream)
- assert progress.current_stage == LearningStage.ERROR_DIAGNOSIS
-
- # ERROR_DIAGNOSIS -> REVIEW (practice answer was correct, no active error records)
- await cap._run_error_diagnosis(progress, stream)
- assert progress.current_stage == LearningStage.REVIEW
-
- # REVIEW -> COMPLETED (no next module)
- await cap._run_review(progress, stream)
- assert progress.current_stage == LearningStage.COMPLETED
-
- # ERROR_DIAGNOSIS makes no LLM call when there are no errors, so 5 total.
- assert cap._call_llm.call_count == 5
-
- # Both quizzes graded in-turn: diagnostic + practice = 2 recorded attempts.
- assert len(progress.quiz_attempts) == 2
- qids = {a.question_id for a in progress.quiz_attempts}
- assert qids == {"dq1", "pq1"}
- assert all(a.is_correct for a in progress.quiz_attempts)
- # Practice question was attributed to kp1; diagnostic carries no KP.
- by_qid = {a.question_id: a for a in progress.quiz_attempts}
- assert by_qid["pq1"].knowledge_point_id == "kp1"
-
- # Review stage initialized the repetition state + queue for the module KP.
- assert "kp1" in progress.repetition_states
- assert any(t.knowledge_point_id == "kp1" for t in progress.review_queue)
-
-
-async def test_e2e_wrong_practice_opens_error_record_and_diagnosis(tmp_path):
- """A wrong practice answer opens an error record, and ERROR_DIAGNOSIS then
- fires an LLM classification that updates the record's error type."""
- cap, service, _store = _make_cap(tmp_path)
- progress = _single_kp_progress()
- # Jump straight to PRACTICE so the test stays focused on the error path.
- progress.current_stage = LearningStage.PRACTICE
- stream = FakeStream()
-
- practice_data = json.dumps(
- {
- "questions": [
- {
- "id": "pq1",
- "question": "Define photosynthesis.",
- "answer": "photosynthesis",
- "type": "short",
- "knowledge_point_id": "kp1",
- }
- ],
- }
- )
- diagnosis_data = json.dumps(
- {
- "diagnoses": [
- {
- "question_id": "pq1",
- "error_type": "deviation",
- "ai_confirmation": "misread the prompt",
- }
- ],
- }
- )
- cap._call_llm = AsyncMock(side_effect=[practice_data, diagnosis_data])
-
- # Wrong answer -> error record opened (application error from non-blank wrong answer).
- stream.inputs = ["a totally wrong answer"]
-
- await cap._run_practice(progress, stream)
- assert progress.current_stage == LearningStage.ERROR_DIAGNOSIS
- assert len(progress.error_records) == 1
- rec = progress.error_records[0]
- assert rec.question_id == "pq1"
- assert rec.knowledge_point_id == "kp1"
- assert rec.status == "active"
-
- await cap._run_error_diagnosis(progress, stream)
- assert progress.current_stage == LearningStage.REVIEW
- # LLM diagnosis overwrote the coarse error_type and recorded its confirmation.
- assert rec.error_type.value == "deviation"
- assert rec.ai_confirmation == "misread the prompt"
- assert cap._call_llm.call_count == 2
-
-
-async def test_e2e_error_diagnosis_skips_gracefully_when_llm_unavailable(tmp_path):
- """When the LLM is unavailable (``_call_llm`` returns None), ERROR_DIAGNOSIS
- marks active records unavailable and still advances to REVIEW."""
- cap, service, _store = _make_cap(tmp_path)
- progress = _single_kp_progress()
- progress.current_stage = LearningStage.PRACTICE
- stream = FakeStream()
-
- practice_data = json.dumps(
- {
- "questions": [
- {
- "id": "pq1",
- "question": "Define photosynthesis.",
- "answer": "photosynthesis",
- "type": "short",
- "knowledge_point_id": "kp1",
- }
- ],
- }
- )
- # Practice produces a quiz; error diagnosis LLM call is skipped (None).
- cap._call_llm = AsyncMock(side_effect=[practice_data, None])
- stream.inputs = ["wrong"]
-
- await cap._run_practice(progress, stream)
- assert len(progress.error_records) == 1
-
- await cap._run_error_diagnosis(progress, stream)
- assert progress.current_stage == LearningStage.REVIEW
- assert progress.error_records[0].ai_confirmation == "error_diagnosis_unavailable"
-
-
-async def test_e2e_multi_kp_walks_each_kp_then_practices(tmp_path):
- """With two KPs in one module, the per-KP loop should run EXPLAIN+FEYNMAN
- twice before reaching PRACTICE."""
- cap, service, _store = _make_cap(tmp_path)
- kp1 = KnowledgePoint(id="kp1", name="A", type=KnowledgeType.CONCEPT, module_id="m1")
- kp2 = KnowledgePoint(id="kp2", name="B", type=KnowledgeType.CONCEPT, module_id="m1")
- mod = LearningModule(id="m1", name="Mod", order=0, knowledge_points=[kp1, kp2])
- progress = LearningProgress(book_id="multi_book")
- progress.modules = [mod]
- progress.current_module_id = "m1"
- progress.current_kp_index = 0
- progress.current_stage = LearningStage.EXPLAIN
- progress.knowledge_types["kp1"] = KnowledgeType.CONCEPT
- progress.knowledge_types["kp2"] = KnowledgeType.CONCEPT
-
- stream = FakeStream()
- passed = json.dumps({"passed": True, "feedback": "ok", "gap": ""})
- cap._call_llm = AsyncMock(
- side_effect=[
- "explain kp1",
- passed, # KP1
- "explain kp2",
- passed, # KP2
- ]
- )
- # Two feynman explanations.
- stream.inputs = ["explanation 1", "explanation 2"]
-
- # KP1: EXPLAIN -> FEYNMAN -> (more KPs) -> EXPLAIN
- await cap._run_explain(progress, stream)
- assert progress.current_stage == LearningStage.FEYNMAN_CHECK
- await cap._run_feynman_check(progress, stream)
- assert progress.current_stage == LearningStage.EXPLAIN
- assert progress.current_kp_index == 1
-
- # KP2: EXPLAIN -> FEYNMAN -> (no more KPs) -> PRACTICE
- await cap._run_explain(progress, stream)
- assert progress.current_stage == LearningStage.FEYNMAN_CHECK
- await cap._run_feynman_check(progress, stream)
- assert progress.current_stage == LearningStage.PRACTICE
- assert progress.mastery_levels["kp1"] == pytest.approx(0.6)
- assert progress.mastery_levels["kp2"] == pytest.approx(0.6)
-
-
-async def test_e2e_review_advances_to_next_module(tmp_path):
- """When a further module exists, REVIEW loops back to EXPLAIN on the next
- module rather than COMPLETED."""
- cap, service, _store = _make_cap(tmp_path)
- kp1 = KnowledgePoint(id="kp1", name="A", type=KnowledgeType.CONCEPT, module_id="m1")
- kp2 = KnowledgePoint(id="kp2", name="B", type=KnowledgeType.CONCEPT, module_id="m2")
- mod1 = LearningModule(id="m1", name="Mod1", order=0, knowledge_points=[kp1])
- mod2 = LearningModule(id="m2", name="Mod2", order=1, knowledge_points=[kp2])
- progress = LearningProgress(book_id="two_module_book")
- progress.modules = [mod1, mod2]
- progress.current_module_id = "m1"
- progress.current_kp_index = 0
- progress.current_stage = LearningStage.REVIEW
- progress.knowledge_types["kp1"] = KnowledgeType.CONCEPT
- progress.knowledge_types["kp2"] = KnowledgeType.CONCEPT
-
- stream = FakeStream()
- cap._call_llm = AsyncMock(return_value="Review content")
-
- await cap._run_review(progress, stream)
- assert progress.current_stage == LearningStage.EXPLAIN
- assert progress.current_module_id == "m2"
- assert progress.current_kp_index == 0
-
-
-async def test_e2e_explain_skip_advances_after_kp(tmp_path):
- """If the EXPLAIN LLM call is skipped (None), the handler should fall through
- to ``_advance_after_kp`` rather than wedging on FEYNMAN_CHECK."""
- cap, service, _store = _make_cap(tmp_path)
- progress = _single_kp_progress()
- progress.current_stage = LearningStage.EXPLAIN
- stream = FakeStream()
-
- cap._call_llm = AsyncMock(return_value=None)
- await cap._run_explain(progress, stream)
- # Single KP -> _advance_after_kp -> PRACTICE.
- assert progress.current_stage == LearningStage.PRACTICE
diff --git a/deeptutor/learning/tests/test_error_diagnosis.py b/deeptutor/learning/tests/test_error_diagnosis.py
deleted file mode 100644
index 10ca18ca9..000000000
--- a/deeptutor/learning/tests/test_error_diagnosis.py
+++ /dev/null
@@ -1,210 +0,0 @@
-"""Tests for the ERROR_DIAGNOSIS stage of the Mastery Path capability.
-
-The stage classifies each active/retrying error record via a single LLM call
-and then advances to REVIEW. When the model is unavailable (``_call_llm``
-returns ``None``) it must degrade gracefully: mark every active record as
-``error_diagnosis_unavailable`` and still advance, never wedge the loop.
-"""
-
-from contextlib import asynccontextmanager
-import json
-from unittest.mock import AsyncMock
-
-import pytest
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import (
- ErrorRecord,
- ErrorType,
- KnowledgePoint,
- KnowledgeType,
- LearningModule,
- LearningProgress,
- LearningStage,
-)
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
-
-
-class FakeStream:
- def __init__(self) -> None:
- self.events: list[tuple[str, str]] = []
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(("stage", name))
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(("content", text))
-
-
-def _make_capability() -> MasteryPathCapability:
- """Build a capability with an in-memory (no-root) store so ``save`` is a
- no-op file-wise, and stub the single LLM seam to a default skip (None)."""
- cap = MasteryPathCapability.__new__(MasteryPathCapability)
- cap._store = LearningStore.__new__(LearningStore)
- cap._store._root = None
- cap._service = LearningService(cap._store)
- cap._scheduler = None
- cap._call_llm = AsyncMock(return_value=None) # type: ignore[method-assign]
- return cap
-
-
-def _make_progress(*, error_records=None) -> LearningProgress:
- progress = LearningProgress(book_id="book1")
- progress.current_stage = LearningStage.ERROR_DIAGNOSIS
- progress.current_module_id = "m1"
- progress.modules = [
- LearningModule(
- id="m1",
- name="Module 1",
- order=0,
- knowledge_points=[
- KnowledgePoint(id="kp1", name="KP1", type=KnowledgeType.CONCEPT, module_id="m1")
- ],
- )
- ]
- if error_records is None:
- error_records = [
- ErrorRecord(
- id="er1",
- question_id="q1",
- knowledge_point_id="kp1",
- module_id="m1",
- error_type=ErrorType.APPLICATION_ERROR,
- status="active",
- )
- ]
- progress.error_records.extend(error_records)
- return progress
-
-
-async def test_error_diagnosis_llm_skip_advances_to_review_and_marks_unavailable():
- """When the LLM is unavailable (``_call_llm`` -> None), every active record
- is flagged unavailable, its prior error_type is preserved, and the stage
- advances to REVIEW rather than wedging on the flaky model."""
- cap = _make_capability()
- cap._call_llm = AsyncMock(return_value=None) # type: ignore[method-assign]
- progress = _make_progress()
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert progress.current_stage == LearningStage.REVIEW
- assert progress.error_records[0].error_type == ErrorType.APPLICATION_ERROR
- assert progress.error_records[0].ai_confirmation == "error_diagnosis_unavailable"
-
-
-async def test_error_diagnosis_uses_extended_timeout():
- """The stage must call the LLM with the longer error-diagnosis budget."""
- cap = _make_capability()
- call_llm = AsyncMock(return_value=None)
- cap._call_llm = call_llm
- progress = _make_progress()
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert call_llm.await_count == 1
- assert call_llm.await_args.kwargs["timeout"] == cap._ERROR_DIAGNOSIS_TIMEOUT_SECONDS
-
-
-async def test_error_diagnosis_no_active_records_skips_to_review():
- """With no active/retrying records there is nothing to diagnose: skip the
- LLM entirely and advance to REVIEW."""
- cap = _make_capability()
- call_llm = AsyncMock(return_value=None)
- cap._call_llm = call_llm
- graduated = ErrorRecord(
- id="er0",
- question_id="q0",
- knowledge_point_id="kp1",
- module_id="m1",
- error_type=ErrorType.APPLICATION_ERROR,
- status="graduated",
- )
- progress = _make_progress(error_records=[graduated])
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert progress.current_stage == LearningStage.REVIEW
- call_llm.assert_not_awaited()
- assert graduated.ai_confirmation == ""
-
-
-async def test_error_diagnosis_applies_llm_diagnoses():
- """A successful diagnosis reclassifies the error_type and records the AI
- confirmation on the matching record, then advances to REVIEW."""
- cap = _make_capability()
- diagnoses = {
- "diagnoses": [
- {
- "question_id": "q1",
- "error_type": "structural",
- "ai_confirmation": "concept gap in prerequisites",
- }
- ]
- }
- cap._call_llm = AsyncMock(return_value=json.dumps(diagnoses, ensure_ascii=False))
- progress = _make_progress()
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert progress.current_stage == LearningStage.REVIEW
- rec = progress.error_records[0]
- assert rec.error_type == ErrorType.KNOWLEDGE_STRUCTURAL
- assert rec.ai_confirmation == "concept gap in prerequisites"
-
-
-async def test_error_diagnosis_ignores_invalid_error_type():
- """A bogus error_type label leaves the existing classification intact while
- still recording any AI confirmation."""
- cap = _make_capability()
- diagnoses = {
- "diagnoses": [
- {
- "question_id": "q1",
- "error_type": "not_a_real_type",
- "ai_confirmation": "kept original type",
- }
- ]
- }
- cap._call_llm = AsyncMock(return_value=json.dumps(diagnoses, ensure_ascii=False))
- progress = _make_progress()
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- rec = progress.error_records[0]
- assert rec.error_type == ErrorType.APPLICATION_ERROR
- assert rec.ai_confirmation == "kept original type"
-
-
-async def test_error_diagnosis_diagnoses_retrying_records():
- """``retrying`` records are active for diagnosis just like ``active`` ones."""
- cap = _make_capability()
- cap._call_llm = AsyncMock(return_value=None) # type: ignore[method-assign]
- retrying = ErrorRecord(
- id="er2",
- question_id="q2",
- knowledge_point_id="kp1",
- module_id="m1",
- error_type=ErrorType.APPLICATION_ERROR,
- status="retrying",
- )
- progress = _make_progress(error_records=[retrying])
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert progress.current_stage == LearningStage.REVIEW
- assert retrying.ai_confirmation == "error_diagnosis_unavailable"
diff --git a/deeptutor/learning/tests/test_feynman_retry.py b/deeptutor/learning/tests/test_feynman_retry.py
deleted file mode 100644
index c1fc8e6a7..000000000
--- a/deeptutor/learning/tests/test_feynman_retry.py
+++ /dev/null
@@ -1,173 +0,0 @@
-"""Tests for the Feynman-check retry limit in the Mastery Path capability."""
-
-from contextlib import asynccontextmanager
-import json
-from unittest.mock import AsyncMock
-
-import pytest
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import (
- KnowledgePoint,
- LearningModule,
- LearningProgress,
- LearningStage,
-)
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
-
-
-class FakeStream:
- """Minimal StreamBus mock for capability testing."""
-
- def __init__(self, user_inputs: list[str] | None = None):
- self._inputs = list(user_inputs or [])
- self._input_idx = 0
- self.events: list[str] = []
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(f"stage:{name}")
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(text)
-
- async def wait_for_input(self, prompt, source="", stage="", timeout=None):
- if self._input_idx < len(self._inputs):
- val = self._inputs[self._input_idx]
- self._input_idx += 1
- return val
- return ""
-
-
-def _make_progress(kp_id="kp1", kp_name="Test KP") -> LearningProgress:
- progress = LearningProgress(book_id="testbook")
- progress.modules = [
- LearningModule(
- id="m1",
- name="M1",
- order=0,
- knowledge_points=[
- KnowledgePoint(id=kp_id, name=kp_name, type="concept", module_id="m1")
- ],
- )
- ]
- progress.current_module_id = "m1"
- progress.current_kp_index = 0
- progress.current_stage = LearningStage.FEYNMAN_CHECK
- return progress
-
-
-def _make_capability(llm_response: str | None) -> MasteryPathCapability:
- """Build a capability without touching the filesystem (no LearningStore root)
- and with the LLM mocked at the handler level via ``_call_llm``."""
- cap = MasteryPathCapability.__new__(MasteryPathCapability)
- store = LearningStore.__new__(LearningStore)
- store._root = None # not used: these tests never save to disk
- cap._store = store
- cap._service = LearningService(store)
- cap._scheduler = None # the Feynman path never touches the scheduler
- # Mock the single LLM entry point so no network/JSON contract is exercised.
- cap._call_llm = AsyncMock(return_value=llm_response) # type: ignore[method-assign]
- # save() is a no-op so the in-memory progress isn't flushed to a missing root.
- cap._service.save = lambda progress: None # type: ignore[method-assign]
- return cap
-
-
-async def test_feynman_3_failures_marks_weak_and_advances_to_practice():
- """After 3 consecutive Feynman failures the KP is marked weak and, since the
- module has a single KP, the stage advances to PRACTICE (was PRACTICE_QUIZ)."""
- failed_response = json.dumps({"passed": False, "feedback": "not quite", "gap": ""})
- progress = _make_progress()
-
- # Fail 3 times. A fresh capability per turn mirrors the per-turn lifecycle.
- for _ in range(3):
- cap = _make_capability(failed_response)
- stream = FakeStream(user_inputs=["my explanation"])
- await cap._run_feynman_check(progress, stream)
-
- # Single KP exhausted -> _advance_after_kp lands on PRACTICE.
- assert progress.current_stage == LearningStage.PRACTICE
- # Mastery marked as weak.
- assert progress.mastery_levels["kp1"] == 0.0
- # Retry counter reached the cap.
- assert progress.feynman_retries["kp1"] == MasteryPathCapability._FEYNMAN_MAX_RETRIES
-
-
-async def test_feynman_failure_loops_back_to_explain():
- """A failure below the retry cap loops back to EXPLAIN and bumps the counter."""
- failed_response = json.dumps({"passed": False, "feedback": "no", "gap": ""})
- progress = _make_progress()
-
- cap = _make_capability(failed_response)
- stream = FakeStream(user_inputs=["my explanation"])
- await cap._run_feynman_check(progress, stream)
-
- assert progress.feynman_retries["kp1"] == 1
- assert progress.current_stage == LearningStage.EXPLAIN
-
-
-async def test_feynman_pass_resets_counter_and_sets_mastery():
- """Passing the Feynman check resets the retry counter, sets the pass-level
- mastery floor, and advances past the per-KP loop."""
- failed_response = json.dumps({"passed": False, "feedback": "no", "gap": ""})
- passed_response = json.dumps({"passed": True, "feedback": "good", "gap": ""})
-
- progress = _make_progress()
-
- # Fail twice (stays below the cap, loops to EXPLAIN each time).
- for _ in range(2):
- cap = _make_capability(failed_response)
- stream = FakeStream(user_inputs=["my explanation"])
- await cap._run_feynman_check(progress, stream)
-
- assert progress.feynman_retries["kp1"] == 2
- assert progress.current_stage == LearningStage.EXPLAIN
-
- # Pass on the 3rd attempt.
- cap = _make_capability(passed_response)
- stream = FakeStream(user_inputs=["my explanation"])
- await cap._run_feynman_check(progress, stream)
-
- # Counter reset, mastery floored at the pass level, single KP -> PRACTICE.
- assert progress.feynman_retries["kp1"] == 0
- assert progress.mastery_levels["kp1"] == MasteryPathCapability._FEYNMAN_PASS_MASTERY
- assert progress.current_stage == LearningStage.PRACTICE
-
-
-async def test_feynman_blank_answer_skips_kp_without_calling_llm():
- """A blank explanation advances past the KP without grading and without an
- LLM call (the per-KP loop must not wedge on an empty answer)."""
- cap = _make_capability(json.dumps({"passed": True, "feedback": "", "gap": ""}))
- progress = _make_progress()
- stream = FakeStream(user_inputs=[""])
-
- await cap._run_feynman_check(progress, stream)
-
- cap._call_llm.assert_not_awaited()
- # Single KP exhausted -> PRACTICE; no retry recorded, no mastery set.
- assert progress.current_stage == LearningStage.PRACTICE
- assert "kp1" not in progress.feynman_retries
- assert "kp1" not in progress.mastery_levels
-
-
-async def test_feynman_llm_skip_preserves_explanation_and_retries():
- """When ``_call_llm`` returns None (stage skipped/degraded), the student's
- explanation is preserved and the turn counts as a (non-passing) retry rather
- than stalling — below the cap it loops back to EXPLAIN."""
- cap = _make_capability(None)
- progress = _make_progress()
- stream = FakeStream(user_inputs=["my explanation"])
-
- await cap._run_feynman_check(progress, stream)
-
- # Explanation retained for a later turn; treated as a failed attempt.
- assert progress.feynman_explanations["kp1"] == "my explanation"
- assert progress.feynman_retries["kp1"] == 1
- assert progress.current_stage == LearningStage.EXPLAIN
diff --git a/deeptutor/learning/tests/test_guided_mastery_updates.py b/deeptutor/learning/tests/test_guided_mastery_updates.py
index 95a9ac418..287444952 100644
--- a/deeptutor/learning/tests/test_guided_mastery_updates.py
+++ b/deeptutor/learning/tests/test_guided_mastery_updates.py
@@ -1,26 +1,21 @@
-"""Tests for Mastery Path mastery updates from in-turn answers.
+"""Tests for Mastery Path mastery updates from graded answers.
The unified post-answer pipeline is ``LearningService.grade_and_record``: it
grades one answer, recomputes mastery (recency-weighted with a low-confidence
cap), advances the spaced-repetition state, rebuilds the review queue, and
-persists. The capability's ``_run_quiz`` folds every interactive answer through
-exactly this pipeline, so mastery is updated in-turn with no server-side
-question store. These tests assert that contract end to end.
+persists. The mastery tools (``mastery_grade``) fold every answer through
+exactly this pipeline, so mastery is updated deterministically with the
+expected answer held server-side. These tests assert that contract end to end.
"""
-from contextlib import asynccontextmanager
-import json
-
import pytest
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
from deeptutor.learning.mastery import compute_mastery
from deeptutor.learning.models import (
KnowledgePoint,
KnowledgeType,
LearningModule,
LearningProgress,
- LearningStage,
)
from deeptutor.learning.scheduler import SpacedRepetitionScheduler
from deeptutor.learning.service import LearningService
@@ -29,30 +24,6 @@ from deeptutor.learning.storage import LearningStore
# ── Helpers ──────────────────────────────────────────────────────────────
-class FakeStream:
- """Minimal StreamBus mock for capability testing."""
-
- def __init__(self, user_inputs: list[str] | None = None):
- self._inputs = list(user_inputs or [])
- self._input_idx = 0
- self.events: list[str] = []
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(f"stage:{name}")
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(text)
-
- async def wait_for_input(self, prompt, source="", stage="", timeout=None):
- if self._input_idx < len(self._inputs):
- val = self._inputs[self._input_idx]
- self._input_idx += 1
- return val
- return ""
-
-
def _make_progress(book_id="book1") -> LearningProgress:
progress = LearningProgress(book_id=book_id)
progress.modules = [
@@ -98,7 +69,7 @@ def test_compute_mastery_partial_correctness_scales():
assert one_of_five < two_of_five < three_of_five
-# ── grade_and_record: the unified in-turn pipeline ─────────────────────────
+# ── grade_and_record: the unified post-answer pipeline ─────────────────────
def test_grade_and_record_correct_updates_capped_mastery_and_persists(tmp_path):
@@ -217,7 +188,7 @@ def test_grade_and_record_blank_wrong_is_metacognitive(tmp_path):
assert progress.quiz_attempts[0].error_type == ErrorType.METACOGNITIVE
-# ── Error-record graduation across attempts (the in-turn lifecycle) ────────
+# ── Error-record graduation across attempts ────────────────────────────────
def test_error_record_graduates_on_later_correct_answer(tmp_path):
@@ -257,103 +228,43 @@ def test_error_record_graduates_on_later_correct_answer(tmp_path):
assert progress.mastery_levels["kp1"] > 0.5
-# ── Capability _run_quiz: mastery updated in-turn, no question store ────────
+# ── Pending-question lifecycle + qualitative recording (loop-driven path) ──
+
+def test_pending_question_set_and_clear_round_trip(tmp_path):
+ from deeptutor.learning.models import PendingQuestion
-async def test_run_quiz_updates_mastery_in_turn(tmp_path):
- """``_run_quiz`` streams each (answer-stripped) question, reads the answer
- off the stream, and folds it through grade_and_record so mastery is updated
- in-turn. Inline answer keys are extracted; no server-side store is written."""
store = LearningStore(root=tmp_path)
- cap = MasteryPathCapability(service=LearningService(store))
+ service = LearningService(store)
progress = _make_progress()
- data = {
- "questions": [
- {"question": "Capital of France?", "answer": "paris", "id": "q1"},
- ]
- }
- stream = FakeStream(user_inputs=["paris"])
-
- correct, total = await cap._run_quiz(progress, stream, data, prefix="diag", attribute_kps=False)
-
- assert (correct, total) == (1, 1)
- assert len(progress.quiz_attempts) == 1
- assert progress.quiz_attempts[0].is_correct is True
+ service.set_pending_question(
+ progress,
+ PendingQuestion(
+ question_id="q1",
+ knowledge_point_id="kp1",
+ module_id="m1",
+ prompt="Capital of France?",
+ expected_answer="paris",
+ ),
+ )
+ assert store.load("book1").pending_question.expected_answer == "paris"
- # The streamed question must NOT leak the answer.
- question_events = [e for e in stream.events if e.startswith("{")]
- assert question_events, "expected a streamed question payload"
- payload = json.loads(question_events[0])
- assert "answer" not in payload["question"]
- assert payload["question_id"] == "q1"
+ service.clear_pending_question(progress)
+ assert progress.pending_question is None
+ assert store.load("book1").pending_question is None
-async def test_run_quiz_wrong_answer_records_no_mastery_gain(tmp_path):
- """A wrong in-turn answer is graded fail-closed and leaves mastery at 0."""
+def test_record_qualitative_pass_and_fail_drive_display_mastery(tmp_path):
store = LearningStore(root=tmp_path)
- cap = MasteryPathCapability(service=LearningService(store))
+ service = LearningService(store)
progress = _make_progress()
- data = {"questions": [{"question": "Capital of France?", "answer": "paris", "id": "q1"}]}
- stream = FakeStream(user_inputs=["london"])
-
- correct, total = await cap._run_quiz(progress, stream, data, prefix="diag", attribute_kps=False)
-
- assert (correct, total) == (0, 1)
- assert progress.quiz_attempts[0].is_correct is False
- assert progress.mastery_levels.get("kp1", 0.0) == 0.0
-
-
-# ── _attribute_kps: round-robin fallback (qids derived internally) ─────────
-
-
-def _kp(kp_id: str, name: str) -> KnowledgePoint:
- return KnowledgePoint(id=kp_id, name=name, type=KnowledgeType.CONCEPT, module_id="m1")
-
-
-def test_attribute_kps_accepts_ids_and_names():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {
- "questions": [
- {"knowledge_point_id": "kp2"},
- {"knowledge_point": "Limits"},
- ]
- }
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"quiz_0": "kp2", "quiz_1": "kp1"}
-
-
-def test_attribute_kps_round_robins_missing_attribution():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {"questions": [{}, {}, {}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"quiz_0": "kp1", "quiz_1": "kp2", "quiz_2": "kp1"}
-
-
-def test_attribute_kps_prefers_explicit_question_id():
- kps = [_kp("kp1", "Limits")]
- data = {"questions": [{"id": "custom", "knowledge_point_id": "kp1"}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"custom": "kp1"}
-
-
-# ── _extract_answers: inline keys vs parallel array ────────────────────────
-
-
-def test_extract_answers_inline_keys():
- data = {"questions": [{"id": "q1", "answer": "a1"}, {"id": "q2", "solution": "a2"}]}
- assert MasteryPathCapability._extract_answers(data, "diag") == {"q1": "a1", "q2": "a2"}
-
+ service.record_qualitative(progress, "kp1", passed=True, evidence="clear explanation")
+ assert progress.qualitative_mastery["kp1"] is True
+ assert progress.mastery_levels["kp1"] == 1.0
+ assert progress.feynman_explanations["kp1"] == "clear explanation"
-def test_extract_answers_parallel_array():
- data = {"questions": [{"id": "q1"}, {"id": "q2"}], "answers": ["a1", "a2"]}
- assert MasteryPathCapability._extract_answers(data, "diag") == {"q1": "a1", "q2": "a2"}
+ service.record_qualitative(progress, "kp1", passed=False)
+ assert progress.qualitative_mastery["kp1"] is False
+ assert progress.mastery_levels["kp1"] <= 0.4
diff --git a/deeptutor/learning/tests/test_llm_integration.py b/deeptutor/learning/tests/test_llm_integration.py
deleted file mode 100644
index d246ef75a..000000000
--- a/deeptutor/learning/tests/test_llm_integration.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""Integration tests for the Mastery Path LLM boundary (``_call_llm``).
-
-The capability owns no pedagogy math; this file pins down the one place it
-touches the model: the bounded-retry / graceful-skip wrapper ``_call_llm`` and
-the JSON helper ``_safe_json``. RAG was removed in the Mastery Path refactor,
-so there is no retrieval/injection to cover here anymore.
-
-``_call_llm`` patches the module-level ``complete`` symbol; the new signature is
-``_call_llm(system_prompt, user_message, progress, stage_name, stream, *, timeout=None)``
-and it returns ``str | None`` (``None`` on skip/exhaustion) — it never raises.
-"""
-
-import asyncio
-from contextlib import asynccontextmanager
-import inspect
-from unittest.mock import AsyncMock, patch
-
-import pytest
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import LearningProgress
-
-
-class FakeStream:
- """Minimal StreamBus stand-in: records stage/content events and replays a
- queued list of student inputs for ``wait_for_input``."""
-
- def __init__(self) -> None:
- self.events: list[tuple[str, str]] = []
- self.inputs: list[str] = []
- self._input_idx = 0
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(("stage", name))
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(("content", text))
-
- async def wait_for_input(self, prompt, source="", timeout=None):
- if self._input_idx < len(self.inputs):
- val = self.inputs[self._input_idx]
- self._input_idx += 1
- return val
- return ""
-
-
-def _progress() -> LearningProgress:
- return LearningProgress(book_id="llm_book")
-
-
-class TestCallLLM:
- """``_call_llm`` calls the real LLM factory and returns its response."""
-
- @pytest.mark.asyncio
- async def test_call_llm_calls_complete(self):
- cap = MasteryPathCapability()
- progress = _progress()
- stream = FakeStream()
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- new_callable=AsyncMock,
- ) as mock_complete:
- mock_complete.return_value = "LLM response"
- result = await cap._call_llm("system", "user", progress, "explain", stream)
- mock_complete.assert_called_once()
- # complete is called with the prompt + system prompt by keyword.
- kwargs = mock_complete.call_args.kwargs
- assert kwargs["prompt"] == "user"
- assert kwargs["system_prompt"] == "system"
- assert result == "LLM response"
-
- @pytest.mark.asyncio
- async def test_call_llm_success_clears_failure_state(self):
- """A successful call clears any prior failure bookkeeping for the stage."""
- cap = MasteryPathCapability()
- progress = _progress()
- progress.stage_failure_counts["explain"] = 1
- progress.stage_failure_notes["explain"] = "prior timeout"
- stream = FakeStream()
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- new_callable=AsyncMock,
- return_value="ok",
- ):
- result = await cap._call_llm("system", "user", progress, "explain", stream)
- assert result == "ok"
- assert "explain" not in progress.stage_failure_counts
- assert "explain" not in progress.stage_failure_notes
-
- def test_call_llm_is_async(self):
- cap = MasteryPathCapability()
- assert hasattr(cap, "_call_llm")
- assert inspect.iscoroutinefunction(cap._call_llm)
-
-
-class TestCallLLMFailureHandling:
- """On failure ``_call_llm`` degrades gracefully — bounded retry then a
- ``None`` return — rather than raising or returning an error payload."""
-
- @pytest.mark.asyncio
- async def test_call_llm_returns_none_on_persistent_error(self):
- """When ``complete`` always raises, ``_call_llm`` returns None (does not
- raise, does not return an error JSON) and records the failure."""
- cap = MasteryPathCapability()
- progress = _progress()
- stream = FakeStream()
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- new_callable=AsyncMock,
- side_effect=Exception("Network down"),
- ) as mock_complete:
- result = await cap._call_llm("system", "user", progress, "explain", stream)
- assert result is None
- # Bounded retry: exactly _STAGE_MAX_FAILURES attempts this turn.
- assert mock_complete.call_count == MasteryPathCapability._STAGE_MAX_FAILURES
- # Failure bookkeeping captured for the cross-turn cumulative gate.
- assert progress.stage_failure_counts.get("explain", 0) >= 1
- assert progress.stage_failure_notes.get("explain") == "Network down"
-
- @pytest.mark.asyncio
- async def test_call_llm_skips_without_calling_when_cumulative_exhausted(self):
- """Once cumulative failures hit the threshold, the stage is skipped on
- the next turn without touching the model at all."""
- cap = MasteryPathCapability()
- progress = _progress()
- progress.stage_failure_counts["explain"] = (
- MasteryPathCapability._STAGE_MAX_CUMULATIVE_FAILURES
- )
- stream = FakeStream()
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- new_callable=AsyncMock,
- return_value="should not be called",
- ) as mock_complete:
- result = await cap._call_llm("system", "user", progress, "explain", stream)
- assert result is None
- mock_complete.assert_not_called()
- # The student sees a "已多次失败" skip notice.
- content = [t for kind, t in stream.events if kind == "content"]
- assert any("多次失败" in t for t in content)
-
- @pytest.mark.asyncio
- async def test_call_llm_handles_timeout(self):
- """A call slower than the timeout is retried then skipped, not awaited
- forever — ``asyncio.wait_for`` bounds each attempt."""
- cap = MasteryPathCapability()
- progress = _progress()
- stream = FakeStream()
-
- async def _hang(*args, **kwargs):
- await asyncio.sleep(10)
- return "too late"
-
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- side_effect=_hang,
- ):
- result = await cap._call_llm(
- "system", "user", progress, "explain", stream, timeout=0.01
- )
- assert result is None
- assert progress.stage_failure_counts.get("explain", 0) >= 1
-
- @pytest.mark.asyncio
- async def test_call_llm_retry_recovers_on_second_attempt(self):
- """A transient failure followed by success returns the response and
- clears the failure record."""
- cap = MasteryPathCapability()
- progress = _progress()
- stream = FakeStream()
- with patch(
- "deeptutor.capabilities.mastery_path.complete",
- new_callable=AsyncMock,
- side_effect=[Exception("flaky"), "recovered"],
- ) as mock_complete:
- result = await cap._call_llm("system", "user", progress, "explain", stream)
- assert result == "recovered"
- assert mock_complete.call_count == 2
- assert "explain" not in progress.stage_failure_counts
-
-
-class TestSafeJson:
- """``_safe_json`` parses LLM JSON, falling back to a default on garbage."""
-
- def test_valid_json(self):
- cap = MasteryPathCapability()
- assert cap._safe_json('{"key": "value"}', {}) == {"key": "value"}
-
- def test_invalid_json_fallback(self):
- cap = MasteryPathCapability()
- assert cap._safe_json("not json", {"fallback": True}) == {"fallback": True}
-
- def test_extracts_from_markdown_fence(self):
- cap = MasteryPathCapability()
- fenced = '```json\n{"questions": []}\n```'
- assert cap._safe_json(fenced, {}) == {"questions": []}
-
- def test_non_dict_response_uses_default(self):
- """A JSON array (non-dict) is not a valid stage payload -> default."""
- cap = MasteryPathCapability()
- assert cap._safe_json("[1, 2, 3]", {"questions": []}) == {"questions": []}
diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.py
new file mode 100644
index 000000000..c1e0b3d44
--- /dev/null
+++ b/deeptutor/learning/tests/test_mastery_tools.py
@@ -0,0 +1,219 @@
+"""Tests for the Mastery Path tools — the seam between the chat-loop tutor and
+the engine. They drive the full loop the tutor uses: build a path, read the
+gate, pose + grade questions, assess qualitative objectives, with the active
+path id injected server-side (never by the model)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from deeptutor.learning.storage import LearningStore
+from deeptutor.tools.mastery_tool import (
+ MasteryAssessTool,
+ MasteryBuildTool,
+ MasteryGradeTool,
+ MasteryQuizTool,
+ MasteryStatusTool,
+)
+
+
+def path_id(tmp_path, monkeypatch):
+ """Point the LearningStore at a temp workspace and yield a stable path id."""
+ monkeypatch.setattr(LearningStore, "__init__", _store_init_factory(tmp_path))
+ return "test_path"
+
+
+def _store_init_factory(root):
+ def _init(self, root_arg=None): # mirrors LearningStore.__init__ signature
+ from pathlib import Path
+
+ self._root = Path(root) / "learning"
+ self._root.mkdir(parents=True, exist_ok=True)
+
+ return _init
+
+
+async def _build_basic(path_id):
+ build = MasteryBuildTool()
+ return await build.execute(
+ _mastery_path_id=path_id,
+ mode="replace",
+ modules=[
+ {
+ "name": "Module 1",
+ "knowledge_points": [
+ {"name": "Truth tables", "type": "memory"},
+ {"name": "Why XOR matters", "type": "concept"},
+ ],
+ }
+ ],
+ )
+
+
+# ── build ───────────────────────────────────────────────────────────────────
+
+
+async def test_build_creates_path(path_id):
+ result = await _build_basic(path_id)
+ assert result.success
+ payload = json.loads(result.content)
+ assert payload["knowledge_points_added"] == 2
+ assert payload["map"]["counts"]["total"] == 2
+
+
+async def test_build_rejects_empty_modules(path_id):
+ result = await MasteryBuildTool().execute(_mastery_path_id=path_id, modules=[])
+ assert result.success is False
+
+
+async def test_build_append_keeps_existing(path_id):
+ await _build_basic(path_id)
+ result = await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ mode="append",
+ modules=[{"name": "Module 2", "knowledge_points": [{"name": "Adders", "type": "procedure"}]}],
+ )
+ payload = json.loads(result.content)
+ assert payload["map"]["counts"]["total"] == 3 # 2 existing + 1 appended
+
+
+async def test_build_unknown_type_defaults_to_concept(path_id):
+ result = await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ modules=[{"name": "M", "knowledge_points": [{"name": "Thing", "type": "nonsense"}]}],
+ )
+ kp = json.loads(result.content)["map"]["modules"][0]["knowledge_points"][0]
+ assert kp["type"] == "concept"
+
+
+# ── status ───────────────────────────────────────────────────────────────────
+
+
+async def test_status_empty_path_asks_for_build(path_id):
+ payload = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ assert payload["status"] == "empty"
+
+
+async def test_status_points_at_first_objective(path_id):
+ await _build_basic(path_id)
+ payload = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ assert payload["status"] == "active"
+ assert payload["next"]["action"] == "probe"
+ assert payload["next"]["knowledge_point_type"] == "memory"
+
+
+async def test_no_path_id_fails_closed():
+ result = await MasteryStatusTool().execute(_mastery_path_id="")
+ assert result.success is False
+
+
+# ── quiz + grade: the deterministic objective gate ───────────────────────────
+
+
+async def test_quiz_then_grade_drives_memory_gate(path_id):
+ await _build_basic(path_id)
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = status["next"]["knowledge_point_id"]
+
+ quiz, grade = MasteryQuizTool(), MasteryGradeTool()
+ mastered = False
+ for _ in range(3):
+ await quiz.execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="2+2?",
+ expected_answer="4",
+ question_type="short",
+ )
+ result = json.loads((await grade.execute(_mastery_path_id=path_id, answer="4")).content)
+ assert result["is_correct"] is True
+ mastered = result["mastered"]
+ # 0.5 -> 0.8 -> 1.0 ≥ 0.9: mastered only after the third correct answer.
+ assert mastered is True
+
+
+async def test_grade_without_pending_fails(path_id):
+ await _build_basic(path_id)
+ result = await MasteryGradeTool().execute(_mastery_path_id=path_id, answer="x")
+ assert result.success is False
+
+
+async def test_quiz_unknown_kp_fails(path_id):
+ await _build_basic(path_id)
+ result = await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id="nope",
+ question="?",
+ expected_answer="x",
+ )
+ assert result.success is False
+
+
+async def test_wrong_answer_does_not_master(path_id):
+ await _build_basic(path_id)
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = status["next"]["knowledge_point_id"]
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id, knowledge_point_id=kp_id, question="2+2?", expected_answer="4"
+ )
+ result = json.loads(
+ (await MasteryGradeTool().execute(_mastery_path_id=path_id, answer="5")).content
+ )
+ assert result["is_correct"] is False
+ assert result["mastered"] is False
+
+
+# ── assess: the qualitative gate ─────────────────────────────────────────────
+
+
+async def test_assess_passes_concept(path_id):
+ await _build_basic(path_id)
+ # Drive past the memory objective so status reaches the concept one.
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ mem_kp = status["next"]["knowledge_point_id"]
+ for _ in range(3):
+ await MasteryQuizTool().execute(
+ _mastery_path_id=path_id, knowledge_point_id=mem_kp, question="q", expected_answer="a"
+ )
+ await MasteryGradeTool().execute(_mastery_path_id=path_id, answer="a")
+
+ status2 = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ concept_kp = status2["next"]["knowledge_point_id"]
+ assert status2["next"]["action"] == "probe"
+ assert status2["next"]["knowledge_point_type"] == "concept"
+
+ result = json.loads(
+ (
+ await MasteryAssessTool().execute(
+ _mastery_path_id=path_id, knowledge_point_id=concept_kp, passed=True, feedback="ok"
+ )
+ ).content
+ )
+ assert result["mastered"] is True
+ assert result["next"]["action"] == "complete"
+
+
+async def test_assess_rejects_quantitative_type(path_id):
+ await _build_basic(path_id)
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ mem_kp = status["next"]["knowledge_point_id"] # a memory objective
+ result = await MasteryAssessTool().execute(
+ _mastery_path_id=path_id, knowledge_point_id=mem_kp, passed=True
+ )
+ assert result.success is False
diff --git a/deeptutor/learning/tests/test_policy.py b/deeptutor/learning/tests/test_policy.py
new file mode 100644
index 000000000..99e579d32
--- /dev/null
+++ b/deeptutor/learning/tests/test_policy.py
@@ -0,0 +1,165 @@
+"""Tests for the Mastery Path policy — the per-type gate and the gate-driven
+"what's next" decision that replaced the old linear stage march.
+
+These assert the two Alpha-style principles the old engine violated:
+
+* a HARD gate — an objective is not mastered (and never advanced past) until
+ its evidence clears the threshold;
+* compression — an already-proven objective is skipped, never re-taught.
+"""
+
+from __future__ import annotations
+
+import time
+
+from deeptutor.learning import policy
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ LearningProgress,
+ PendingQuestion,
+ RepetitionState,
+ ReviewTask,
+)
+
+
+def _progress(*kps: KnowledgePoint) -> LearningProgress:
+ progress = LearningProgress(book_id="b1")
+ progress.modules = [
+ LearningModule(id="m1", name="M1", order=0, knowledge_points=list(kps))
+ ]
+ progress.current_module_id = "m1"
+ for kp in kps:
+ progress.knowledge_types[kp.id] = kp.type
+ return progress
+
+
+def _kp(kp_id: str, kp_type: KnowledgeType, name: str = "") -> KnowledgePoint:
+ return KnowledgePoint(id=kp_id, name=name or kp_id, type=kp_type, module_id="m1")
+
+
+# ── per-type gate ──────────────────────────────────────────────────────────
+
+
+def test_memory_gate_requires_high_quantitative_mastery():
+ kp = _kp("kp1", KnowledgeType.MEMORY)
+ progress = _progress(kp)
+ progress.mastery_levels["kp1"] = 0.8
+ assert policy.is_mastered(progress, kp) is False
+ progress.mastery_levels["kp1"] = 0.9
+ assert policy.is_mastered(progress, kp) is True
+
+
+def test_procedure_gate_uses_same_quantitative_bar():
+ kp = _kp("kp1", KnowledgeType.PROCEDURE)
+ progress = _progress(kp)
+ progress.mastery_levels["kp1"] = 0.89
+ assert policy.is_mastered(progress, kp) is False
+
+
+def test_concept_gate_is_qualitative_not_quantitative():
+ """A high accuracy score must NOT unlock a concept — only the qualitative
+ flag does (a concept is gated by an explanation, not string matching)."""
+ kp = _kp("kp1", KnowledgeType.CONCEPT)
+ progress = _progress(kp)
+ progress.mastery_levels["kp1"] = 1.0 # accuracy is high…
+ assert policy.is_mastered(progress, kp) is False # …but the gate is qualitative
+ progress.qualitative_mastery["kp1"] = True
+ assert policy.is_mastered(progress, kp) is True
+
+
+def test_objective_status_new_learning_mastered():
+ kp = _kp("kp1", KnowledgeType.MEMORY)
+ progress = _progress(kp)
+ assert policy.objective_status(progress, kp) == "new"
+ from deeptutor.learning.models import QuizAttempt
+
+ progress.quiz_attempts.append(
+ QuizAttempt(question_id="q", knowledge_point_id="kp1", is_correct=False)
+ )
+ assert policy.objective_status(progress, kp) == "learning"
+ progress.mastery_levels["kp1"] = 0.95
+ assert policy.objective_status(progress, kp) == "mastered"
+
+
+# ── next_objective: gate is the cursor, mastered objectives are skipped ─────
+
+
+def test_next_objective_skips_mastered_and_returns_first_open():
+ kp1, kp2 = _kp("kp1", KnowledgeType.MEMORY), _kp("kp2", KnowledgeType.MEMORY)
+ progress = _progress(kp1, kp2)
+ progress.mastery_levels["kp1"] = 0.95 # already proven -> compression
+ step = policy.next_objective(progress)
+ assert step.knowledge_point_id == "kp2"
+ assert step.action == "probe"
+
+
+def test_next_objective_new_is_probe_then_practice_when_seen():
+ kp = _kp("kp1", KnowledgeType.PROCEDURE)
+ progress = _progress(kp)
+ assert policy.next_objective(progress).action == "probe"
+ from deeptutor.learning.models import QuizAttempt
+
+ progress.quiz_attempts.append(
+ QuizAttempt(question_id="q", knowledge_point_id="kp1", is_correct=False)
+ )
+ assert policy.next_objective(progress).action == "practice"
+
+
+def test_next_objective_qualitative_type_recommends_assess():
+ kp = _kp("kp1", KnowledgeType.DESIGN)
+ progress = _progress(kp)
+ progress.qualitative_mastery["kp1"] = False # seen but not passed
+ assert policy.next_objective(progress).action == "assess"
+
+
+def test_next_objective_pending_question_takes_precedence():
+ kp = _kp("kp1", KnowledgeType.MEMORY)
+ progress = _progress(kp)
+ progress.pending_question = PendingQuestion(
+ question_id="q1", knowledge_point_id="kp1", prompt="?", expected_answer="x"
+ )
+ step = policy.next_objective(progress)
+ assert step.action == "answer_pending"
+ assert step.pending_prompt == "?"
+
+
+def test_next_objective_due_review_beats_new_ground():
+ kp1, kp2 = _kp("kp1", KnowledgeType.MEMORY), _kp("kp2", KnowledgeType.MEMORY)
+ progress = _progress(kp1, kp2)
+ progress.mastery_levels["kp1"] = 0.95 # mastered, but due for review
+ progress.review_queue = [
+ ReviewTask(
+ id="r1",
+ knowledge_point_id="kp1",
+ knowledge_type=KnowledgeType.MEMORY,
+ due_at=time.time() - 10,
+ priority=1,
+ state=RepetitionState(next_review_at=time.time() - 10),
+ )
+ ]
+ step = policy.next_objective(progress)
+ assert step.action == "review"
+ assert step.knowledge_point_id == "kp1"
+
+
+def test_next_objective_complete_when_all_mastered():
+ kp = _kp("kp1", KnowledgeType.MEMORY)
+ progress = _progress(kp)
+ progress.mastery_levels["kp1"] = 0.95
+ assert policy.next_objective(progress).action == "complete"
+
+
+# ── map_summary ─────────────────────────────────────────────────────────────
+
+
+def test_map_summary_counts_and_completion():
+ kp1, kp2 = _kp("kp1", KnowledgeType.MEMORY), _kp("kp2", KnowledgeType.CONCEPT)
+ progress = _progress(kp1, kp2)
+ progress.mastery_levels["kp1"] = 0.95
+ summary = policy.map_summary(progress)
+ assert summary["counts"] == {"mastered": 1, "learning": 0, "new": 1, "total": 2}
+ assert summary["complete"] is False
+ progress.qualitative_mastery["kp2"] = True
+ assert policy.map_summary(progress)["complete"] is True
diff --git a/deeptutor/learning/tests/test_question_attribution.py b/deeptutor/learning/tests/test_question_attribution.py
deleted file mode 100644
index 505c5e395..000000000
--- a/deeptutor/learning/tests/test_question_attribution.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""Tests for per-question knowledge point attribution.
-
-The capability maps each generated question to a knowledge point via
-``MasteryPathCapability._attribute_kps``. Question IDs are derived internally
-from each item (``question_id``/``id`` key, else ``<prefix>_<index>``) rather
-than supplied by the caller. LLM-supplied labels (id or name) win; any
-un-attributed question is distributed round-robin across the module's KPs so
-attribution does not bias toward the first KP.
-"""
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import KnowledgePoint, KnowledgeType
-
-
-def _kp(kp_id: str, name: str) -> KnowledgePoint:
- return KnowledgePoint(id=kp_id, name=name, type=KnowledgeType.CONCEPT, module_id="m1")
-
-
-def test_attribute_kps_accepts_ids_and_names():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {
- "questions": [
- {"knowledge_point_id": "kp2"},
- {"knowledge_point": "Limits"},
- ]
- }
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- # qids are derived as "<prefix>_<index>" since no id/question_id is present.
- assert result == {"quiz_0": "kp2", "quiz_1": "kp1"}
-
-
-def test_attribute_kps_round_robins_missing_attribution():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {"questions": [{}, {}, {}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"quiz_0": "kp1", "quiz_1": "kp2", "quiz_2": "kp1"}
-
-
-def test_attribute_kps_uses_explicit_question_ids():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {
- "questions": [
- {"question_id": "qA", "knowledge_point_id": "kp1"},
- {"id": "qB", "knowledge_point": "Derivatives"},
- ]
- }
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"qA": "kp1", "qB": "kp2"}
-
-
-def test_attribute_kps_mixes_labels_and_round_robin_fallback():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- # Middle question carries an explicit label; the others fall back to
- # round-robin keyed on positional index (i % len(kps)).
- data = {"questions": [{}, {"knowledge_point": "Limits"}, {}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"quiz_0": "kp1", "quiz_1": "kp1", "quiz_2": "kp1"}
-
-
-def test_attribute_kps_supports_exercises_key():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- data = {"exercises": [{"kp": "kp2"}, {"kp_id": "kp1"}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "ex")
-
- assert result == {"ex_0": "kp2", "ex_1": "kp1"}
-
-
-def test_attribute_kps_unknown_label_falls_back_to_round_robin():
- kps = [_kp("kp1", "Limits"), _kp("kp2", "Derivatives")]
- # An unrecognized label cannot resolve; it falls back to round-robin.
- data = {"questions": [{"knowledge_point": "Topology"}]}
-
- result = MasteryPathCapability._attribute_kps(data, kps, "quiz")
-
- assert result == {"quiz_0": "kp1"}
-
-
-def test_attribute_kps_no_kps_yields_empty_ids():
- data = {"questions": [{"knowledge_point_id": "kp1"}, {}]}
-
- result = MasteryPathCapability._attribute_kps(data, [], "quiz")
-
- # With no module KPs, nothing can be attributed and round-robin is skipped.
- assert result == {"quiz_0": "", "quiz_1": ""}
diff --git a/deeptutor/learning/tests/test_timeout_degradation.py b/deeptutor/learning/tests/test_timeout_degradation.py
deleted file mode 100644
index 48b806c56..000000000
--- a/deeptutor/learning/tests/test_timeout_degradation.py
+++ /dev/null
@@ -1,435 +0,0 @@
-"""Tests for the LLM bounded-retry + per-stage graceful-degradation logic.
-
-The Mastery Path capability funnels every model call through a single method,
-``MasteryPathCapability._call_llm(system, user, progress, stage_name, stream,
-*, timeout=None)``. That method owns the resilience policy:
-
- * up to ``_STAGE_MAX_FAILURES`` attempts per turn, then return ``None``;
- * a cross-turn cumulative gate (``_STAGE_MAX_CUMULATIVE_FAILURES``) that skips
- the call entirely once a stage has failed too often across turns;
- * bookkeeping in ``stage_failure_counts`` / ``stage_failure_notes`` that a
- successful call clears.
-
-Each stage handler degrades by branching on a ``None`` return. These tests
-exercise both halves: ``_call_llm`` itself (by patching the underlying
-``complete``) and each handler's ``None`` branch (by stubbing ``cap._call_llm``
-to return ``None`` directly).
-
-RAG was removed, so there is no longer any RAG-timeout path to test.
-"""
-
-from contextlib import asynccontextmanager
-import json
-from unittest.mock import AsyncMock
-
-import pytest
-
-from deeptutor.capabilities.mastery_path import MasteryPathCapability
-from deeptutor.learning.models import (
- ErrorRecord,
- ErrorType,
- KnowledgePoint,
- KnowledgeType,
- LearningModule,
- LearningProgress,
- LearningStage,
-)
-from deeptutor.learning.scheduler import SpacedRepetitionScheduler
-from deeptutor.learning.service import LearningService
-from deeptutor.learning.storage import LearningStore
-
-
-class FakeStream:
- """Minimal StreamBus stand-in: records stage/content events and replays a
- queued list of student inputs for ``wait_for_input``."""
-
- def __init__(self) -> None:
- self.events: list[tuple[str, str]] = []
- self.inputs: list[str] = []
- self._input_idx = 0
-
- @asynccontextmanager
- async def stage(self, name, source="", metadata=None):
- self.events.append(("stage", name))
- yield
-
- async def content(self, text, source="", stage="", metadata=None):
- self.events.append(("content", text))
-
- async def wait_for_input(self, prompt, source="", timeout=None):
- if self._input_idx < len(self.inputs):
- val = self.inputs[self._input_idx]
- self._input_idx += 1
- return val
- return ""
-
- def content_texts(self) -> list[str]:
- return [t for kind, t in self.events if kind == "content"]
-
-
-def _make_cap(tmp_path) -> MasteryPathCapability:
- """A real capability wired to a tmp-path store/service/scheduler."""
- store = LearningStore(root=tmp_path)
- service = LearningService(store)
- return MasteryPathCapability(
- service=service, scheduler=SpacedRepetitionScheduler(), store=store
- )
-
-
-def _progress_with_module() -> LearningProgress:
- kp = KnowledgePoint(id="kp1", name="Test KP", type=KnowledgeType.MEMORY, module_id="m1")
- mod = LearningModule(id="m1", name="Test Module", order=0, knowledge_points=[kp])
- progress = LearningProgress(book_id="book1")
- progress.modules = [mod]
- progress.current_module_id = "m1"
- progress.knowledge_types["kp1"] = KnowledgeType.MEMORY
- progress.current_stage = LearningStage.EXPLAIN
- return progress
-
-
-# ── _call_llm: bounded retry on failure ───────────────────────────────────
-
-
-async def test_call_llm_retries_then_returns_none_and_records_failure(tmp_path, monkeypatch):
- """Every attempt raising should exhaust _STAGE_MAX_FAILURES retries, return
- None, and record the failure count + note (no exception escapes)."""
- cap = _make_cap(tmp_path)
- import deeptutor.capabilities.mastery_path as mp_mod
-
- complete_mock = AsyncMock(side_effect=RuntimeError("LLM unavailable"))
- monkeypatch.setattr(mp_mod, "complete", complete_mock)
-
- progress = _progress_with_module()
- stream = FakeStream()
-
- result = await cap._call_llm("system", "user", progress, "explain", stream)
-
- assert result is None
- # One increment per failed attempt.
- assert complete_mock.call_count == MasteryPathCapability._STAGE_MAX_FAILURES
- assert progress.stage_failure_counts["explain"] == MasteryPathCapability._STAGE_MAX_FAILURES
- assert progress.stage_failure_notes["explain"] # non-empty note recorded
- # The exhausted-retries degradation message is streamed.
- assert any("暂时不可用" in t for t in stream.content_texts())
-
-
-async def test_call_llm_success_clears_prior_failures(tmp_path, monkeypatch):
- """A successful call clears any prior failure count + note for the stage."""
- cap = _make_cap(tmp_path)
- import deeptutor.capabilities.mastery_path as mp_mod
-
- monkeypatch.setattr(mp_mod, "complete", AsyncMock(return_value="ok response"))
-
- progress = _progress_with_module()
- progress.stage_failure_counts["explain"] = 2
- progress.stage_failure_notes["explain"] = "previous timeout"
- stream = FakeStream()
-
- result = await cap._call_llm("system", "user", progress, "explain", stream)
-
- assert result == "ok response"
- assert "explain" not in progress.stage_failure_counts
- assert "explain" not in progress.stage_failure_notes
-
-
-async def test_call_llm_cumulative_gate_skips_without_calling(tmp_path, monkeypatch):
- """Once cumulative failures hit the threshold, _call_llm returns None
- without calling the model and streams the 'multiple failures' message."""
- cap = _make_cap(tmp_path)
- import deeptutor.capabilities.mastery_path as mp_mod
-
- complete_mock = AsyncMock(return_value="should not be called")
- monkeypatch.setattr(mp_mod, "complete", complete_mock)
-
- progress = _progress_with_module()
- progress.stage_failure_counts["explain"] = MasteryPathCapability._STAGE_MAX_CUMULATIVE_FAILURES
- stream = FakeStream()
-
- result = await cap._call_llm("system", "user", progress, "explain", stream)
-
- assert result is None
- complete_mock.assert_not_called()
- assert any("多次失败" in t for t in stream.content_texts())
-
-
-async def test_call_llm_below_cumulative_gate_still_retries(tmp_path, monkeypatch):
- """Below the cumulative gate, a flaky stage still attempts its retries and
- accumulates further failures."""
- cap = _make_cap(tmp_path)
- import deeptutor.capabilities.mastery_path as mp_mod
-
- complete_mock = AsyncMock(side_effect=RuntimeError("LLM unavailable"))
- monkeypatch.setattr(mp_mod, "complete", complete_mock)
-
- progress = _progress_with_module()
- progress.stage_failure_counts["explain"] = 2 # below threshold of 4
- stream = FakeStream()
-
- result = await cap._call_llm("system", "user", progress, "explain", stream)
-
- assert result is None
- assert complete_mock.call_count == MasteryPathCapability._STAGE_MAX_FAILURES
- assert progress.stage_failure_counts["explain"] > 2
-
-
-async def test_call_llm_timeout_counts_as_failure(tmp_path, monkeypatch):
- """A model call that exceeds the per-call timeout is treated as a failure
- and folds into the retry/skip bookkeeping."""
- import asyncio
-
- cap = _make_cap(tmp_path)
- import deeptutor.capabilities.mastery_path as mp_mod
-
- async def _slow(*args, **kwargs):
- await asyncio.sleep(10)
- return "too late"
-
- monkeypatch.setattr(mp_mod, "complete", _slow)
-
- progress = _progress_with_module()
- stream = FakeStream()
-
- # Tiny timeout so the wait_for fires immediately.
- result = await cap._call_llm("system", "user", progress, "diagnostic", stream, timeout=0.01)
-
- assert result is None
- assert progress.stage_failure_counts["diagnostic"] == MasteryPathCapability._STAGE_MAX_FAILURES
-
-
-# ── Stage handlers degrade on a None LLM result ────────────────────────────
-
-
-async def test_explain_skip_advances_after_kp(tmp_path):
- """When EXPLAIN's LLM call is skipped (None), the handler advances via
- _advance_after_kp rather than to FEYNMAN_CHECK. With a single KP that lands
- on PRACTICE."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.EXPLAIN
- stream = FakeStream()
-
- await cap._run_explain(progress, stream)
-
- # Single KP -> _advance_after_kp goes to PRACTICE, not FEYNMAN_CHECK.
- assert progress.current_stage == LearningStage.PRACTICE
-
-
-async def test_practice_skip_advances_to_error_diagnosis(tmp_path):
- """When PRACTICE's LLM call is skipped (None), advance straight to
- ERROR_DIAGNOSIS without running a quiz."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.PRACTICE
- stream = FakeStream()
-
- await cap._run_practice(progress, stream)
-
- assert progress.current_stage == LearningStage.ERROR_DIAGNOSIS
- # No quiz ran, so no attempts were recorded.
- assert progress.quiz_attempts == []
-
-
-async def test_diagnostic_skip_sets_empty_result_and_advances(tmp_path):
- """When DIAGNOSTIC's LLM call is skipped (None), an empty DiagnosticResult
- is stored and the stage advances to EXPLAIN."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.DIAGNOSTIC
- stream = FakeStream()
-
- await cap._run_diagnostic(progress, stream)
-
- assert progress.current_stage == LearningStage.EXPLAIN
- assert progress.diagnostic is not None
- assert progress.diagnostic.total_questions == 0
- assert progress.diagnostic.correct_count == 0
-
-
-async def test_feynman_skip_persists_unevaluated_explanation(tmp_path):
- """When FEYNMAN_CHECK's LLM judge is skipped (None) and the student gave a
- non-blank explanation, the explanation is persisted as unevaluated and the
- '未评估' feedback is streamed."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.FEYNMAN_CHECK
- stream = FakeStream()
- stream.inputs = ["My explanation of the concept"]
-
- await cap._run_feynman_check(progress, stream)
-
- # The unevaluated explanation is preserved for next time.
- assert progress.feynman_explanations.get("kp1") == "My explanation of the concept"
- assert any("未评估" in t for t in stream.content_texts())
- # A skipped judge is a non-pass: it counts as a retry, then advances.
- assert progress.current_stage != LearningStage.FEYNMAN_CHECK
-
-
-async def test_feynman_blank_skips_judge_and_advances(tmp_path):
- """A blank explanation short-circuits FEYNMAN_CHECK: no LLM judge, advance
- via _advance_after_kp."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value="should not be called")
- progress = _progress_with_module()
- progress.current_stage = LearningStage.FEYNMAN_CHECK
- stream = FakeStream()
- stream.inputs = [""] # blank
-
- await cap._run_feynman_check(progress, stream)
-
- cap._call_llm.assert_not_called()
- # Single KP -> _advance_after_kp -> PRACTICE.
- assert progress.current_stage == LearningStage.PRACTICE
-
-
-async def test_feynman_pass_clears_explanation_and_seeds_mastery(tmp_path):
- """A passing judge clears any prior unevaluated explanation and seeds
- mastery at the Feynman pass floor."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(
- return_value=json.dumps({"passed": True, "feedback": "很好", "gap": ""})
- )
- progress = _progress_with_module()
- progress.current_stage = LearningStage.FEYNMAN_CHECK
- progress.feynman_explanations["kp1"] = "previous unevaluated explanation"
- stream = FakeStream()
- stream.inputs = ["My explanation"]
-
- await cap._run_feynman_check(progress, stream)
-
- assert "kp1" not in progress.feynman_explanations
- assert progress.mastery_levels["kp1"] == pytest.approx(
- MasteryPathCapability._FEYNMAN_PASS_MASTERY
- )
- # Single KP, passed -> _advance_after_kp -> PRACTICE.
- assert progress.current_stage == LearningStage.PRACTICE
-
-
-async def test_error_diagnosis_skip_marks_records_unavailable(tmp_path):
- """When ERROR_DIAGNOSIS's LLM call is skipped (None), each active record is
- annotated 'error_diagnosis_unavailable' and the stage advances to REVIEW."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.ERROR_DIAGNOSIS
- progress.error_records = [
- ErrorRecord(
- id="er1",
- question_id="q1",
- knowledge_point_id="kp1",
- module_id="m1",
- error_type=ErrorType.APPLICATION_ERROR,
- status="active",
- )
- ]
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert progress.current_stage == LearningStage.REVIEW
- assert progress.error_records[0].ai_confirmation == "error_diagnosis_unavailable"
-
-
-async def test_error_diagnosis_passes_timeout_through(tmp_path, monkeypatch):
- """ERROR_DIAGNOSIS uses the dedicated, shorter timeout when it calls the
- model."""
- cap = _make_cap(tmp_path)
- captured: dict = {}
-
- async def _spy(system, user, progress, stage_name, stream, *, timeout=None):
- captured["timeout"] = timeout
- captured["stage_name"] = stage_name
- return None
-
- cap._call_llm = _spy
- progress = _progress_with_module()
- progress.current_stage = LearningStage.ERROR_DIAGNOSIS
- progress.error_records = [
- ErrorRecord(
- id="er1",
- question_id="q1",
- knowledge_point_id="kp1",
- module_id="m1",
- error_type=ErrorType.APPLICATION_ERROR,
- status="active",
- )
- ]
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- assert captured["stage_name"] == "error_diagnosis"
- assert captured["timeout"] == MasteryPathCapability._ERROR_DIAGNOSIS_TIMEOUT_SECONDS
-
-
-async def test_error_diagnosis_no_active_records_skips_llm(tmp_path):
- """With no active/retrying error records, ERROR_DIAGNOSIS makes no LLM call
- and advances to REVIEW."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value="should not be called")
- progress = _progress_with_module()
- progress.current_stage = LearningStage.ERROR_DIAGNOSIS
- progress.error_records = []
- stream = FakeStream()
-
- await cap._run_error_diagnosis(progress, stream)
-
- cap._call_llm.assert_not_called()
- assert progress.current_stage == LearningStage.REVIEW
-
-
-async def test_review_skip_uses_static_fallback_text(tmp_path):
- """When REVIEW's LLM call is skipped (None), a static fallback review prompt
- is streamed and the stage advances (COMPLETED for the last module)."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- progress.current_stage = LearningStage.REVIEW
- stream = FakeStream()
-
- await cap._run_review(progress, stream)
-
- assert progress.current_stage == LearningStage.COMPLETED
- assert any("请回顾" in t for t in stream.content_texts())
- # The review queue/states were still initialized despite the LLM skip.
- assert "kp1" in progress.repetition_states
-
-
-async def test_review_advances_to_next_module_explain(tmp_path):
- """When a next module exists, REVIEW loops back to EXPLAIN on the next
- module even when the LLM call is skipped."""
- cap = _make_cap(tmp_path)
- cap._call_llm = AsyncMock(return_value=None)
- progress = _progress_with_module()
- kp2 = KnowledgePoint(id="kp2", name="Second KP", type=KnowledgeType.MEMORY, module_id="m2")
- progress.modules.append(
- LearningModule(id="m2", name="Module 2", order=1, knowledge_points=[kp2])
- )
- progress.knowledge_types["kp2"] = KnowledgeType.MEMORY
- progress.current_stage = LearningStage.REVIEW
- stream = FakeStream()
-
- await cap._run_review(progress, stream)
-
- assert progress.current_stage == LearningStage.EXPLAIN
- assert progress.current_module_id == "m2"
- assert progress.current_kp_index == 0
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 89a3a0b00..ac7f22f20 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -9,6 +9,7 @@ from typing import Any
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
from deeptutor.tools.exec_tool import ExecTool
+from deeptutor.tools.mastery_tool import MASTERY_TOOL_TYPES
from deeptutor.tools.prompting import load_prompt_hints
logger = logging.getLogger(__name__)
@@ -1451,6 +1452,9 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
GithubTool,
AskUserTool,
CronTool,
+ # Mastery Path tools — auto-mounted only when a path is active on the turn
+ # (see ToolMountFlags.has_mastery); the chat agent loop drives them.
+ *MASTERY_TOOL_TYPES,
)
# Tools whose implementation is parked while we redesign them. NOT loaded
diff --git a/deeptutor/tools/mastery_tool.py b/deeptutor/tools/mastery_tool.py
new file mode 100644
index 000000000..e54ca4952
--- /dev/null
+++ b/deeptutor/tools/mastery_tool.py
@@ -0,0 +1,520 @@
+"""Mastery Path tools — the seam between the chat-loop tutor and the pure
+mastery engine (:mod:`deeptutor.learning`).
+
+These five tools are auto-mounted only when a mastery path is active on the
+turn (see ``ToolMountFlags.has_mastery``). The chat agent loop IS the tutor;
+these tools let it read the gate and record outcomes, while the pedagogy —
+what to teach, how to question, when to explain — stays the model's job. The
+arithmetic (mastery, gate, spaced repetition) stays in the engine.
+
+The active path id is injected server-side by the pipeline as
+``_mastery_path_id``; the model never supplies it. Each call constructs a
+fresh store + service (matching the REST router) so concurrent turns can't
+race on a shared object.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any
+import uuid
+
+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
+
+# ``learning.models`` and ``learning.policy`` only depend on pydantic — safe to
+# import at module load. ``learning.service`` / ``storage`` / ``scheduler``
+# reach the path service (and so the runtime + tool registry), so importing
+# them here would close an import cycle: tool_registry -> builtin ->
+# mastery_tool -> service -> path_service -> runtime -> tool_registry. They are
+# imported lazily inside the call paths instead (same pattern as the other
+# builtin tools).
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ PendingQuestion,
+)
+from deeptutor.learning.policy import (
+ QUALITATIVE_TYPES,
+ display_mastery,
+ find_knowledge_point,
+ gate_threshold,
+ is_mastered,
+ map_summary,
+ next_objective,
+)
+
+if TYPE_CHECKING:
+ from deeptutor.learning.service import LearningService
+
+# Tool names the pipeline mounts together when a mastery path is active. Kept
+# here so the mount policy and the registration list can't disagree.
+MASTERY_TOOL_NAMES: tuple[str, ...] = (
+ "mastery_status",
+ "mastery_quiz",
+ "mastery_grade",
+ "mastery_assess",
+ "mastery_build",
+)
+
+_QUESTION_TYPES = ("choice", "short", "open")
+_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
+
+
+def _new_service() -> LearningService:
+ from deeptutor.learning.service import LearningService
+ from deeptutor.learning.storage import LearningStore
+
+ return LearningService(LearningStore())
+
+
+def _resolve_path_id(kwargs: dict[str, Any]) -> str:
+ return str(kwargs.get("_mastery_path_id") or "").strip()
+
+
+def _json_result(payload: dict[str, Any], *, meta_key: str, success: bool = True) -> ToolResult:
+ return ToolResult(
+ content=json.dumps(payload, ensure_ascii=False),
+ success=success,
+ metadata={meta_key: payload},
+ )
+
+
+def _no_path_result() -> ToolResult:
+ return ToolResult(
+ content="No mastery path is active on this turn; mastery tools are unavailable.",
+ success=False,
+ )
+
+
+class MasteryStatusTool(BaseTool):
+ """Read the current objective + map snapshot. Call FIRST every turn."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="mastery_status",
+ description=(
+ "Read the learner's mastery path: the next objective to work on "
+ "(decided by a hard mastery gate), any question awaiting an "
+ "answer, due reviews, and a map of every objective's status "
+ "(new / learning / mastered). Call this FIRST on every mastery "
+ "turn — it tells you what to do; never guess the next objective."
+ ),
+ parameters=[],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ path_id = _resolve_path_id(kwargs)
+ if not path_id:
+ return _no_path_result()
+ service = _new_service()
+ progress = service.get_or_create(path_id)
+ if not any(module.knowledge_points for module in progress.modules):
+ return _json_result(
+ {
+ "status": "empty",
+ "message": (
+ "No mastery path has been built yet. Design one from the "
+ "learner's materials and call mastery_build."
+ ),
+ },
+ meta_key="mastery_status",
+ )
+ payload = {
+ "status": "active",
+ "next": next_objective(progress).to_dict(),
+ "map": map_summary(progress),
+ }
+ return _json_result(payload, meta_key="mastery_status")
+
+
+class MasteryQuizTool(BaseTool):
+ """Register an objective-type question; the engine holds the answer."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="mastery_quiz",
+ description=(
+ "Pose a question for a MEMORY or PROCEDURE objective and register "
+ "its expected answer with the engine (so grading is deterministic "
+ "and you never re-state the answer later). After calling this, "
+ "present the question to the learner — via ask_user for a tight "
+ "loop, or as your reply — then call mastery_grade with their "
+ "answer. For CONCEPT / DESIGN objectives use mastery_assess instead."
+ ),
+ parameters=[
+ ToolParameter(
+ name="knowledge_point_id",
+ type="string",
+ description="Objective id from mastery_status (verbatim).",
+ ),
+ ToolParameter(
+ name="question",
+ type="string",
+ description="The question text shown to the learner.",
+ ),
+ ToolParameter(
+ name="expected_answer",
+ type="string",
+ description="The correct answer, used only server-side for grading.",
+ ),
+ ToolParameter(
+ name="question_type",
+ type="string",
+ description=(
+ "'choice' (exact match), 'short' (exact / fuzzy for ≤30 "
+ "chars), or 'open' (keyword overlap). Default 'short'."
+ ),
+ required=False,
+ default="short",
+ enum=list(_QUESTION_TYPES),
+ ),
+ ToolParameter(
+ name="options",
+ type="array",
+ description="Choice labels, when question_type='choice'.",
+ required=False,
+ items={"type": "string"},
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ path_id = _resolve_path_id(kwargs)
+ if not path_id:
+ return _no_path_result()
+ kp_id = str(kwargs.get("knowledge_point_id") or "").strip()
+ question = str(kwargs.get("question") or "").strip()
+ expected = str(kwargs.get("expected_answer") or "").strip()
+ if not kp_id or not question or not expected:
+ return ToolResult(
+ content="mastery_quiz needs knowledge_point_id, question, and expected_answer.",
+ success=False,
+ )
+ q_type = str(kwargs.get("question_type") or "short").strip().lower()
+ if q_type not in _QUESTION_TYPES:
+ q_type = "short"
+ options = [str(o) for o in (kwargs.get("options") or []) if str(o).strip()]
+
+ service = _new_service()
+ progress = service.get_or_create(path_id)
+ kp, module_id, _ = find_knowledge_point(progress, kp_id)
+ if kp is None:
+ return ToolResult(
+ content=f"Unknown objective {kp_id!r}; call mastery_status for valid ids.",
+ success=False,
+ )
+ pending = PendingQuestion(
+ question_id=uuid.uuid4().hex,
+ knowledge_point_id=kp_id,
+ module_id=module_id,
+ prompt=question,
+ question_type=q_type,
+ expected_answer=expected,
+ options=options,
+ )
+ service.set_pending_question(progress, pending)
+ return _json_result(
+ {
+ "status": "registered",
+ "knowledge_point_id": kp_id,
+ "question": question,
+ "options": options,
+ "instruction": (
+ "Present this question to the learner now, then call "
+ "mastery_grade with their answer."
+ ),
+ },
+ meta_key="mastery_quiz",
+ )
+
+
+class MasteryGradeTool(BaseTool):
+ """Grade the learner's answer to the pending question (deterministic)."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="mastery_grade",
+ description=(
+ "Grade the learner's answer to the question you registered with "
+ "mastery_quiz. Grading is deterministic against the stored "
+ "expected answer; this updates mastery, advances spaced "
+ "repetition, and tells you whether the objective's gate is now "
+ "cleared. Then give the learner feedback."
+ ),
+ parameters=[
+ ToolParameter(
+ name="answer",
+ type="string",
+ description="The learner's answer, verbatim.",
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ path_id = _resolve_path_id(kwargs)
+ if not path_id:
+ return _no_path_result()
+ from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+
+ answer = str(kwargs.get("answer") or "")
+ service = _new_service()
+ scheduler = SpacedRepetitionScheduler()
+ progress = service.get_or_create(path_id)
+ pending = progress.pending_question
+ if pending is None:
+ return ToolResult(
+ content="No question is awaiting an answer. Pose one with mastery_quiz first.",
+ success=False,
+ )
+ is_correct = service.grade_and_record(
+ progress,
+ question_id=pending.question_id,
+ knowledge_point_id=pending.knowledge_point_id,
+ module_id=pending.module_id,
+ user_answer=answer,
+ expected_answer=pending.expected_answer,
+ question_type=pending.question_type,
+ scheduler=scheduler,
+ )
+ service.clear_pending_question(progress)
+ kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
+ mastered = bool(kp and is_mastered(progress, kp))
+ payload = {
+ "is_correct": is_correct,
+ "knowledge_point_id": pending.knowledge_point_id,
+ "mastery": round(display_mastery(progress, kp), 3) if kp else 0.0,
+ "threshold": round(gate_threshold(kp.type), 3) if kp else 0.0,
+ "mastered": mastered,
+ "next": next_objective(progress).to_dict(),
+ }
+ return _json_result(payload, meta_key="mastery_grade")
+
+
+class MasteryAssessTool(BaseTool):
+ """Record the qualitative (CONCEPT / DESIGN) gate from a Feynman check."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="mastery_assess",
+ description=(
+ "Record your judgement of a CONCEPT or DESIGN objective after the "
+ "learner explains it in their own words (a Feynman-style check). "
+ "Pass passed=true only when the explanation is correct and "
+ "complete enough to count as mastery — this is the gate for these "
+ "objective types. For MEMORY / PROCEDURE objectives use "
+ "mastery_quiz + mastery_grade instead."
+ ),
+ parameters=[
+ ToolParameter(
+ name="knowledge_point_id",
+ type="string",
+ description="Objective id from mastery_status (verbatim).",
+ ),
+ ToolParameter(
+ name="passed",
+ type="boolean",
+ description="True if the explanation demonstrates mastery.",
+ ),
+ ToolParameter(
+ name="feedback",
+ type="string",
+ description="Short note on what was strong or missing (stored as evidence).",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ path_id = _resolve_path_id(kwargs)
+ if not path_id:
+ return _no_path_result()
+ kp_id = str(kwargs.get("knowledge_point_id") or "").strip()
+ if not kp_id:
+ return ToolResult(content="mastery_assess needs a knowledge_point_id.", success=False)
+ passed = bool(kwargs.get("passed"))
+ feedback = str(kwargs.get("feedback") or "").strip()
+
+ service = _new_service()
+ progress = service.get_or_create(path_id)
+ kp, _, _ = find_knowledge_point(progress, kp_id)
+ if kp is None:
+ return ToolResult(
+ content=f"Unknown objective {kp_id!r}; call mastery_status for valid ids.",
+ success=False,
+ )
+ if kp.type not in QUALITATIVE_TYPES:
+ return ToolResult(
+ content=(
+ f"Objective {kp.name!r} is a {kp.type.value} type — gate it with "
+ "mastery_quiz + mastery_grade, not mastery_assess."
+ ),
+ success=False,
+ )
+ service.record_qualitative(progress, kp_id, passed=passed, evidence=feedback)
+ payload = {
+ "knowledge_point_id": kp_id,
+ "passed": passed,
+ "mastered": is_mastered(progress, kp),
+ "mastery": round(display_mastery(progress, kp), 3),
+ "next": next_objective(progress).to_dict(),
+ }
+ return _json_result(payload, meta_key="mastery_assess")
+
+
+class MasteryBuildTool(BaseTool):
+ """Create / extend the skill map from objectives the tutor designed."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="mastery_build",
+ description=(
+ "Create or extend the learner's mastery path. Design modules and "
+ "their knowledge points from the learner's materials (use rag / "
+ "read_source first when materials are attached) and pass them "
+ "here. Each knowledge point needs a 'type': memory (facts), "
+ "procedure (step-by-step skills), concept (ideas to understand), "
+ "or design (open-ended judgement). Use mode='replace' to start "
+ "fresh or 'append' to add to an existing path."
+ ),
+ parameters=[
+ ToolParameter(
+ name="modules",
+ type="array",
+ description=(
+ "Ordered modules: each {name, knowledge_points: [{name, "
+ "type}]}. type is one of memory/procedure/concept/design."
+ ),
+ items={
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "knowledge_points": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "type": {
+ "type": "string",
+ "enum": sorted(_ALLOWED_KP_TYPES),
+ },
+ },
+ "required": ["name"],
+ },
+ },
+ },
+ "required": ["name", "knowledge_points"],
+ },
+ ),
+ ToolParameter(
+ name="mode",
+ type="string",
+ description="'replace' (default) starts fresh; 'append' adds modules.",
+ required=False,
+ default="replace",
+ enum=["replace", "append"],
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ path_id = _resolve_path_id(kwargs)
+ if not path_id:
+ return _no_path_result()
+ mode = str(kwargs.get("mode") or "replace").strip().lower()
+ if mode not in {"replace", "append"}:
+ mode = "replace"
+
+ service = _new_service()
+ progress = service.get_or_create(path_id)
+ offset = len(progress.modules) if mode == "append" else 0
+ new_modules, error = _parse_modules(kwargs.get("modules"), path_id, offset)
+ if error:
+ return ToolResult(content=error, success=False)
+
+ combined = (list(progress.modules) + new_modules) if mode == "append" else new_modules
+ service.replace_modules(progress, combined)
+ progress.pending_question = None # a rebuilt map invalidates any open question
+ if combined:
+ progress.current_module_id = combined[0].id
+ progress.current_kp_index = 0
+ service.save(progress)
+ kp_count = sum(len(m.knowledge_points) for m in new_modules)
+ return _json_result(
+ {
+ "status": "built",
+ "mode": mode,
+ "modules_added": len(new_modules),
+ "knowledge_points_added": kp_count,
+ "map": map_summary(progress),
+ },
+ meta_key="mastery_build",
+ )
+
+
+def _parse_modules(
+ raw_modules: Any, path_id: str, offset: int
+) -> tuple[list[LearningModule], str | None]:
+ """Validate the model-designed module tree into engine models.
+
+ Ids are generated server-side (``<path>_m<i>_kp<j>``) so the model never
+ controls storage keys; unknown knowledge types fall back to 'concept'.
+ """
+ if not isinstance(raw_modules, list) or not raw_modules:
+ return [], "mastery_build needs a non-empty 'modules' array."
+ modules: list[LearningModule] = []
+ for i, raw in enumerate(raw_modules):
+ if not isinstance(raw, dict):
+ continue
+ index = offset + i
+ name = str(raw.get("name") or "").strip()[:200]
+ if not name:
+ continue
+ module_id = f"{path_id}_m{index}"
+ kps: list[KnowledgePoint] = []
+ for j, raw_kp in enumerate(raw.get("knowledge_points") or []):
+ if not isinstance(raw_kp, dict):
+ continue
+ kp_name = str(raw_kp.get("name") or "").strip()[:200]
+ if len(kp_name) < 2:
+ continue
+ kp_type = str(raw_kp.get("type") or "concept").strip().lower()
+ if kp_type not in _ALLOWED_KP_TYPES:
+ kp_type = "concept"
+ kps.append(
+ KnowledgePoint(
+ id=f"{module_id}_kp{j}",
+ name=kp_name,
+ type=KnowledgeType(kp_type),
+ module_id=module_id,
+ )
+ )
+ if not kps:
+ continue
+ modules.append(
+ LearningModule(id=module_id, name=name, order=index, knowledge_points=kps)
+ )
+ if not modules:
+ return [], "No valid modules: each module needs a name and at least one knowledge point."
+ return modules, None
+
+
+MASTERY_TOOL_TYPES: tuple[type[BaseTool], ...] = (
+ MasteryStatusTool,
+ MasteryQuizTool,
+ MasteryGradeTool,
+ MasteryAssessTool,
+ MasteryBuildTool,
+)
+
+
+__all__ = [
+ "MASTERY_TOOL_NAMES",
+ "MASTERY_TOOL_TYPES",
+ "MasteryStatusTool",
+ "MasteryQuizTool",
+ "MasteryGradeTool",
+ "MasteryAssessTool",
+ "MasteryBuildTool",
+]
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index eb60bec02..db446be40 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -19,6 +19,7 @@ import {
Database,
FileSearch,
Globe,
+ GraduationCap,
Lightbulb,
MessageSquare,
Microscope,
@@ -243,6 +244,17 @@ const CAPABILITIES: CapabilityDef[] = [
allowedTools: [],
defaultTools: [],
},
+ {
+ value: "mastery_path",
+ label: "Mastery Path",
+ description: "Mastery-based tutoring with a hard gate",
+ icon: GraduationCap,
+ // The mastery tools (status/quiz/grade/assess/build) auto-mount server-side
+ // when this capability is active; rag auto-mounts when a KB is attached.
+ // These are only the extra optional tools the tutor may also reach for.
+ allowedTools: ["web_search", "code_execution"],
+ defaultTools: [],
+ },
];
interface KnowledgeBase {
diff --git a/web/app/(workspace)/learning/[bookId]/page.tsx b/web/app/(workspace)/learning/[bookId]/page.tsx
deleted file mode 100644
index 98f7d85d6..000000000
--- a/web/app/(workspace)/learning/[bookId]/page.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-"use client";
-
-import { useTranslation } from "react-i18next";
-import ComingSoon from "@/components/common/ComingSoon";
-
-/**
- * Per-book Mastery Path runner — shelved alongside the index route (see
- * ``../page.tsx``). Kept as a "coming soon" placeholder so deep links don't
- * 404; the original runner is in git history and the backend/components are
- * intact.
- */
-export default function MasteryPathBookPage() {
- const { t } = useTranslation();
- return <ComingSoon label={t("Mastery Path")} />;
-}
diff --git a/web/app/(workspace)/learning/page.tsx b/web/app/(workspace)/learning/page.tsx
index 803f617c6..2020de7a3 100644
--- a/web/app/(workspace)/learning/page.tsx
+++ b/web/app/(workspace)/learning/page.tsx
@@ -1,17 +1,339 @@
"use client";
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
-import ComingSoon from "@/components/common/ComingSoon";
+import {
+ GraduationCap,
+ Loader2,
+ RotateCcw,
+ Trash2,
+ CircleCheck,
+ CircleDot,
+ Circle,
+ MessageSquare,
+} from "lucide-react";
+
+import {
+ fetchAllProgress,
+ fetchMasteryMap,
+ deleteProgress,
+ redoProgress,
+ type ProgressSummary,
+ type MasteryMapResult,
+ type ObjectiveStatus,
+} from "@/lib/learning-api";
/**
- * Mastery Path is hidden from the product nav while it's being reworked. The
- * route is kept so a hand-typed ``/learning`` URL lands on a graceful
- * "coming soon" placeholder instead of a 404. The previous implementation
- * lives in git history; the reusable pieces (``components/learning/*``,
- * ``lib/learning-api.ts``) and the backend (``deeptutor/learning``) are all
- * untouched and ready to be wired back in.
+ * Mastery Path dashboard — the persistent "screen" of the mastery experience.
+ *
+ * The tutoring itself runs on the chat agent loop (pick "Mastery Path" mode in
+ * Chat); this page is the map of where the learner stands. It reads the
+ * gate-accurate snapshot from ``/progress/{id}/map`` (per-type status computed
+ * by ``deeptutor.learning.policy``) so the colours here agree with the gate the
+ * tutor enforces. A path is keyed by its chat session, so "Continue" reopens
+ * that session in mastery mode.
*/
export default function MasteryPathPage() {
- const { t } = useTranslation();
- return <ComingSoon label={t("Mastery Path")} />;
+ const { i18n } = useTranslation();
+ const zh = i18n.language?.toLowerCase().startsWith("zh");
+ const tr = useCallback((cn: string, en: string) => (zh ? cn : en), [zh]);
+ const router = useRouter();
+
+ const [paths, setPaths] = useState<ProgressSummary[]>([]);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [detail, setDetail] = useState<MasteryMapResult | null>(null);
+ const [loadingList, setLoadingList] = useState(true);
+ const [loadingDetail, setLoadingDetail] = useState(false);
+
+ const loadList = useCallback(async () => {
+ setLoadingList(true);
+ try {
+ const result = await fetchAllProgress();
+ const withContent = result.summaries
+ .filter((s) => s.kp_count > 0)
+ .sort((a, b) => b.updated_at - a.updated_at);
+ setPaths(withContent);
+ setSelected((prev) => prev ?? withContent[0]?.book_id ?? null);
+ } catch {
+ setPaths([]);
+ } finally {
+ setLoadingList(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ loadList();
+ }, [loadList]);
+
+ useEffect(() => {
+ if (!selected) {
+ setDetail(null);
+ return;
+ }
+ let cancelled = false;
+ setLoadingDetail(true);
+ fetchMasteryMap(selected)
+ .then((result) => {
+ if (!cancelled) setDetail(result);
+ })
+ .catch(() => {
+ if (!cancelled) setDetail(null);
+ })
+ .finally(() => {
+ if (!cancelled) setLoadingDetail(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [selected]);
+
+ const handleDelete = useCallback(
+ async (pathId: string) => {
+ if (!window.confirm(tr("确定删除这条精通之路?", "Delete this mastery path?"))) return;
+ await deleteProgress(pathId);
+ if (selected === pathId) setSelected(null);
+ await loadList();
+ },
+ [selected, loadList, tr],
+ );
+
+ const handleRedo = useCallback(
+ async (pathId: string) => {
+ if (
+ !window.confirm(
+ tr(
+ "重置进度?知识点保留,但掌握度与复习计划清空。",
+ "Reset progress? Objectives are kept, but mastery and reviews are cleared.",
+ ),
+ )
+ )
+ return;
+ await redoProgress(pathId);
+ const result = await fetchMasteryMap(pathId);
+ setDetail(result);
+ },
+ [tr],
+ );
+
+ return (
+ <div className="flex h-full">
+ {/* Path list */}
+ <aside className="w-64 shrink-0 border-r border-[var(--border)] flex flex-col">
+ <header className="px-4 py-3 border-b border-[var(--border)]">
+ <div className="flex items-center gap-2 text-[var(--foreground)]">
+ <GraduationCap className="w-4 h-4" />
+ <h1 className="text-sm font-semibold">{tr("精通之路", "Mastery Path")}</h1>
+ </div>
+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">
+ {tr("掌握式学习:硬门槛 + 间隔复习", "Mastery-based learning: hard gate + spaced review")}
+ </p>
+ </header>
+ <div className="flex-1 overflow-y-auto p-2 space-y-1">
+ {loadingList ? (
+ <div className="flex items-center justify-center py-8 text-[var(--muted-foreground)]">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ </div>
+ ) : paths.length === 0 ? (
+ <p className="px-2 py-3 text-xs text-[var(--muted-foreground)] leading-relaxed">
+ {tr(
+ "还没有精通之路。去「对话」选择 Mastery Path 模式,让导师根据你的材料建一条。",
+ "No paths yet. Open Chat, pick Mastery Path mode, and ask the tutor to build one from your materials.",
+ )}
+ </p>
+ ) : (
+ paths.map((path) => (
+ <button
+ key={path.book_id}
+ onClick={() => setSelected(path.book_id)}
+ className={`w-full text-left px-3 py-2 rounded-md transition-colors cursor-pointer ${
+ selected === path.book_id
+ ? "bg-[var(--primary)]/10 ring-1 ring-[var(--primary)]/30"
+ : "hover:bg-[var(--accent)]"
+ }`}
+ >
+ <div className="truncate text-sm text-[var(--foreground)]">{path.name}</div>
+ <div className="mt-0.5 text-xs text-[var(--muted-foreground)]">
+ {path.kp_count} {tr("个知识点", "objectives")} · {path.avg_mastery_pct}%
+ </div>
+ </button>
+ ))
+ )}
+ </div>
+ <footer className="p-2 border-t border-[var(--border)]">
+ <button
+ onClick={() => router.push("/chat")}
+ className="w-full flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-md bg-[var(--primary)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity cursor-pointer"
+ >
+ <MessageSquare className="w-3.5 h-3.5" />
+ {tr("新建(在对话中)", "New (in Chat)")}
+ </button>
+ </footer>
+ </aside>
+
+ {/* Selected path map */}
+ <section className="flex-1 overflow-y-auto">
+ {loadingDetail ? (
+ <div className="flex items-center justify-center h-full text-[var(--muted-foreground)]">
+ <Loader2 className="w-5 h-5 animate-spin" />
+ </div>
+ ) : !detail ? (
+ <div className="flex flex-col items-center justify-center h-full text-center px-6 text-[var(--muted-foreground)]">
+ <GraduationCap className="w-10 h-10 mb-3 opacity-40" />
+ <p className="text-sm max-w-sm leading-relaxed">
+ {tr(
+ "选择一条精通之路查看进度地图,或在「对话」里用 Mastery Path 模式开始。",
+ "Select a path to see its progress map, or start one in Chat with Mastery Path mode.",
+ )}
+ </p>
+ </div>
+ ) : (
+ <MapView
+ result={detail}
+ zh={!!zh}
+ tr={tr}
+ onContinue={() => selected && router.push(`/chat/${encodeURIComponent(selected)}`)}
+ onRedo={() => selected && handleRedo(selected)}
+ onDelete={() => selected && handleDelete(selected)}
+ />
+ )}
+ </section>
+ </div>
+ );
+}
+
+const STATUS_META: Record<
+ ObjectiveStatus,
+ { cn: string; en: string; className: string }
+> = {
+ mastered: { cn: "已掌握", en: "Mastered", className: "text-green-500" },
+ learning: { cn: "学习中", en: "Learning", className: "text-yellow-500" },
+ new: { cn: "未开始", en: "Not started", className: "text-[var(--muted-foreground)]" },
+};
+
+const ACTION_LABEL: Record<string, { cn: string; en: string }> = {
+ probe: { cn: "先探查是否已掌握", en: "Probe — test out first" },
+ practice: { cn: "练习直到达标", en: "Practice until the gate clears" },
+ assess: { cn: "用自己的话解释", en: "Explain it in your own words" },
+ review: { cn: "到期复习", en: "Due for review" },
+ answer_pending: { cn: "有待回答的问题", en: "A question is awaiting your answer" },
+ complete: { cn: "已全部掌握 🎉", en: "All mastered 🎉" },
+};
+
+function StatusIcon({ status }: { status: ObjectiveStatus }) {
+ const cls = `w-3 h-3 shrink-0 ${STATUS_META[status].className}`;
+ if (status === "mastered") return <CircleCheck className={cls} />;
+ if (status === "learning") return <CircleDot className={cls} />;
+ return <Circle className={cls} />;
+}
+
+function MapView({
+ result,
+ zh,
+ tr,
+ onContinue,
+ onRedo,
+ onDelete,
+}: {
+ result: MasteryMapResult;
+ zh: boolean;
+ tr: (cn: string, en: string) => string;
+ onContinue: () => void;
+ onRedo: () => void;
+ onDelete: () => void;
+}) {
+ const { map, next } = result;
+ const pct = map.counts.total
+ ? Math.round((map.counts.mastered / map.counts.total) * 100)
+ : 0;
+ const action = ACTION_LABEL[next.action] ?? { cn: next.reason, en: next.reason };
+
+ return (
+ <div className="max-w-2xl mx-auto px-6 py-5">
+ {/* Header: progress + next + actions */}
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
+ <span>
+ {map.counts.mastered}/{map.counts.total} {tr("已掌握", "mastered")}
+ </span>
+ {map.due_reviews > 0 && (
+ <span className="text-yellow-600">
+ · {map.due_reviews} {tr("项待复习", "due for review")}
+ </span>
+ )}
+ </div>
+ <div className="mt-1.5 h-1.5 w-full rounded-full bg-[var(--accent)] overflow-hidden">
+ <div
+ className="h-full bg-green-500 transition-all"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <button
+ onClick={onRedo}
+ title={tr("重置进度", "Reset progress")}
+ className="p-1.5 rounded-md text-[var(--muted-foreground)] hover:bg-[var(--accent)] cursor-pointer"
+ >
+ <RotateCcw className="w-4 h-4" />
+ </button>
+ <button
+ onClick={onDelete}
+ title={tr("删除", "Delete")}
+ className="p-1.5 rounded-md text-[var(--muted-foreground)] hover:bg-red-500/10 hover:text-red-500 cursor-pointer"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+
+ {/* Next step */}
+ <button
+ onClick={onContinue}
+ className="mt-4 w-full text-left rounded-lg border border-[var(--border)] hover:border-[var(--primary)]/40 hover:bg-[var(--accent)] p-3 transition-colors cursor-pointer"
+ >
+ <div className="text-xs text-[var(--muted-foreground)]">{tr("接下来", "Next")}</div>
+ <div className="mt-0.5 text-sm font-medium text-[var(--foreground)]">
+ {next.action === "complete"
+ ? tr(action.cn, action.en)
+ : `${next.knowledge_point_name} — ${tr(action.cn, action.en)}`}
+ </div>
+ <div className="mt-1 text-xs text-[var(--primary)]">
+ {tr("在对话中继续辅导 →", "Continue tutoring in Chat →")}
+ </div>
+ </button>
+
+ {/* Module / objective map */}
+ <div className="mt-5 space-y-4">
+ {map.modules.map((module) => (
+ <div key={module.id}>
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-[var(--foreground)]">{module.name}</h3>
+ <span className="text-xs text-[var(--muted-foreground)]">
+ {module.mastered}/{module.total}
+ </span>
+ </div>
+ <div className="mt-1.5 space-y-1">
+ {module.knowledge_points.map((kp) => (
+ <div
+ key={kp.id}
+ className="flex items-center gap-2 px-2 py-1 rounded-md text-sm"
+ >
+ <StatusIcon status={kp.status} />
+ <span className="flex-1 truncate text-[var(--foreground)]">{kp.name}</span>
+ <span className="text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {kp.type}
+ </span>
+ <span className={`text-xs ${STATUS_META[kp.status].className}`}>
+ {zh ? STATUS_META[kp.status].cn : STATUS_META[kp.status].en}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
}
diff --git a/web/components/learning/AnswerInput.tsx b/web/components/learning/AnswerInput.tsx
deleted file mode 100644
index f230c1481..000000000
--- a/web/components/learning/AnswerInput.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { Loader2, Send } from "lucide-react";
-import { useTranslation } from "react-i18next";
-import MarkdownRenderer from "@/components/common/MarkdownRenderer";
-import type { QuizQuestion } from "@/components/learning/StageContent";
-
-interface AnswerInputProps {
- prompt: string;
- /** When present and it has `options`, render selectable choices. */
- question: QuizQuestion | null;
- submitting: boolean;
- onSubmit: (text: string) => void;
-}
-
-export default function AnswerInput({
- prompt,
- question,
- submitting,
- onSubmit,
-}: AnswerInputProps) {
- const { t } = useTranslation();
- const [text, setText] = useState("");
- const isChoice = (question?.options.length ?? 0) > 0;
-
- const submit = (value: string) => {
- const answer = value.trim();
- if (!answer || submitting) return;
- onSubmit(answer);
- };
-
- return (
- <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
- {prompt && (
- <div className="mb-3 text-sm text-[var(--foreground)]">
- <MarkdownRenderer content={prompt} enableMath variant="compact" />
- </div>
- )}
-
- {isChoice ? (
- <div className="grid gap-2">
- {question!.options.map((opt, i) => {
- // Submit the option's leading label (e.g. "A") when the option is
- // formatted "A. ...", otherwise the full option text.
- const labelMatch = opt.match(/^([A-Za-z0-9]+)[.)]\s/);
- const value = labelMatch ? labelMatch[1] : opt;
- return (
- <button
- key={i}
- type="button"
- disabled={submitting}
- onClick={() => submit(value)}
- className="flex w-full items-center gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] px-4 py-3 text-left text-sm text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/50 hover:bg-[var(--primary)]/5 disabled:cursor-not-allowed disabled:opacity-60"
- >
- <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-[var(--border)] text-xs text-[var(--muted-foreground)]">
- {labelMatch ? labelMatch[1] : i + 1}
- </span>
- <span className="flex-1">
- {labelMatch ? opt.slice(labelMatch[0].length) : opt}
- </span>
- </button>
- );
- })}
- </div>
- ) : (
- <>
- <textarea
- value={text}
- onChange={(e) => setText(e.target.value)}
- onKeyDown={(e) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") submit(text);
- }}
- disabled={submitting}
- placeholder={t("masteryPath.inputPlaceholder")}
- className="min-h-[96px] w-full resize-y rounded-lg border border-[var(--border)] bg-[var(--background)] p-3 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--primary)]/40 focus:outline-none"
- />
- <div className="mt-3 flex justify-end">
- <button
- type="button"
- onClick={() => submit(text)}
- disabled={submitting || !text.trim()}
- className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
- >
- {submitting ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Send className="h-3.5 w-3.5" />
- )}
- {t("masteryPath.submit")}
- </button>
- </div>
- </>
- )}
- </div>
- );
-}
diff --git a/web/components/learning/CreateModuleDialog.tsx b/web/components/learning/CreateModuleDialog.tsx
deleted file mode 100644
index 8b5acb71b..000000000
--- a/web/components/learning/CreateModuleDialog.tsx
+++ /dev/null
@@ -1,558 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useState } from "react";
-import { FileText, Loader2, Plus, Trash2, X } from "lucide-react";
-import { useTranslation } from "react-i18next";
-
-import {
- importFromBook,
- initModules,
- generateModulesFromNotebook,
- type ModuleInit,
-} from "@/lib/learning-api";
-import { bookApi } from "@/lib/book-api";
-import type { Book } from "@/lib/book-types";
-import {
- listNotebooks,
- getNotebook,
- type NotebookSummary,
- type NotebookRecordItem,
-} from "@/lib/notebook-api";
-
-interface CreateModuleDialogProps {
- open: boolean;
- onClose: () => void;
- onCreated: () => void;
-}
-
-type Source = "manual" | "book" | "notebook";
-
-interface KpRow {
- name: string;
- type: string;
-}
-
-/**
- * Derive a stable, collision-resistant id from a human label without ever
- * surfacing it in the UI. crypto.randomUUID keeps this opaque (the old code
- * leaked `Date.now()`-based ids through a free-text field).
- */
-function genId(prefix: string): string {
- const rand =
- typeof crypto !== "undefined" && "randomUUID" in crypto
- ? crypto.randomUUID().slice(0, 8)
- : Math.random().toString(36).slice(2, 10);
- return `${prefix}_${rand}`;
-}
-
-export default function CreateModuleDialog({
- open,
- onClose,
- onCreated,
-}: CreateModuleDialogProps) {
- const { t } = useTranslation();
- const [source, setSource] = useState<Source>("manual");
-
- // ── Manual ──
- const [moduleName, setModuleName] = useState("");
- const [kpRows, setKpRows] = useState<KpRow[]>([
- { name: "", type: "concept" },
- ]);
-
- // ── Book ──
- const [books, setBooks] = useState<Book[]>([]);
- const [selectedBookId, setSelectedBookId] = useState("");
- const [bookChapters, setBookChapters] = useState<
- { title: string; learning_objectives: string[] }[]
- >([]);
- const [loadingBooks, setLoadingBooks] = useState(false);
- const [loadingChapters, setLoadingChapters] = useState(false);
-
- // ── Notebook ──
- const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);
- const [selectedNotebook, setSelectedNotebook] = useState("");
- const [notebookRecords, setNotebookRecords] = useState<NotebookRecordItem[]>(
- [],
- );
- const [selectedRecordIds, setSelectedRecordIds] = useState<Set<string>>(
- new Set(),
- );
- const [loadingNotebooks, setLoadingNotebooks] = useState(false);
- const [loadingRecords, setLoadingRecords] = useState(false);
-
- // ── Shared ──
- const [submitting, setSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- // Lazy-load the list for whichever non-manual source is active.
- useEffect(() => {
- if (!open) return;
- if (source === "book" && books.length === 0) {
- setLoadingBooks(true);
- bookApi
- .list()
- .then((data) => setBooks(data.books ?? []))
- .catch(() => setError(t("masteryPath.loadBooksFailed")))
- .finally(() => setLoadingBooks(false));
- }
- if (source === "notebook" && notebooks.length === 0) {
- setLoadingNotebooks(true);
- listNotebooks()
- .then(setNotebooks)
- .catch(() => setError(t("masteryPath.loadNotebooksFailed")))
- .finally(() => setLoadingNotebooks(false));
- }
- }, [open, source, books.length, notebooks.length, t]);
-
- useEffect(() => {
- if (!selectedBookId) {
- setBookChapters([]);
- return;
- }
- setBookChapters([]);
- setLoadingChapters(true);
- bookApi
- .get(selectedBookId)
- .then((data) => setBookChapters(data.spine?.chapters ?? []))
- .catch(() => setError(t("masteryPath.loadChaptersFailed")))
- .finally(() => setLoadingChapters(false));
- }, [selectedBookId, t]);
-
- useEffect(() => {
- if (!selectedNotebook) {
- setNotebookRecords([]);
- setSelectedRecordIds(new Set());
- return;
- }
- setLoadingRecords(true);
- getNotebook(selectedNotebook)
- .then((data) => setNotebookRecords(data.records ?? []))
- .catch(() => setError(t("masteryPath.loadRecordsFailed")))
- .finally(() => setLoadingRecords(false));
- }, [selectedNotebook, t]);
-
- const resetState = useCallback(() => {
- setSource("manual");
- setModuleName("");
- setKpRows([{ name: "", type: "concept" }]);
- setSelectedBookId("");
- setBookChapters([]);
- setSelectedNotebook("");
- setNotebookRecords([]);
- setSelectedRecordIds(new Set());
- setSubmitting(false);
- setError(null);
- }, []);
-
- const handleClose = useCallback(() => {
- resetState();
- onClose();
- }, [resetState, onClose]);
-
- // ── Submit (one entry point, branches per source) ──
- const handleSubmit = useCallback(async () => {
- setSubmitting(true);
- setError(null);
- try {
- if (source === "manual") {
- const validKps = kpRows.filter((r) => r.name.trim());
- if (validKps.length === 0) {
- setError(t("masteryPath.moduleNameRequired"));
- return;
- }
- const bookId = genId("manual");
- const moduleId = genId("m");
- const modules: ModuleInit[] = [
- {
- id: moduleId,
- name: moduleName.trim() || t("masteryPath.untitledModule"),
- order: 0,
- pass_threshold: 0.7,
- knowledge_points: validKps.map((kp) => ({
- id: genId("kp"),
- name: kp.name.trim(),
- type: kp.type,
- module_id: moduleId,
- })),
- },
- ];
- await initModules(bookId, modules);
- } else if (source === "book") {
- if (!selectedBookId || bookChapters.length === 0) return;
- const chapters = bookChapters.map((ch) => ({
- title: ch.title,
- knowledge_points: ch.learning_objectives ?? [],
- }));
- await importFromBook(selectedBookId, chapters);
- } else {
- if (!selectedNotebook || selectedRecordIds.size === 0) return;
- const bookId = `nb_${selectedNotebook}`;
- const records = notebookRecords
- .filter((r) => selectedRecordIds.has(r.id))
- .map((r) => ({
- id: r.id,
- type: r.type,
- title: r.title,
- output: r.output,
- }));
- await generateModulesFromNotebook(
- bookId,
- selectedNotebook,
- records.slice(0, 20),
- );
- }
- onCreated();
- handleClose();
- } catch {
- setError(
- source === "manual"
- ? t("masteryPath.createModuleFailed")
- : source === "book"
- ? t("masteryPath.importBookFailed")
- : t("masteryPath.importNotebookFailed"),
- );
- } finally {
- setSubmitting(false);
- }
- }, [
- source,
- kpRows,
- moduleName,
- selectedBookId,
- bookChapters,
- selectedNotebook,
- selectedRecordIds,
- notebookRecords,
- onCreated,
- handleClose,
- t,
- ]);
-
- if (!open) return null;
-
- const sources: { key: Source; label: string }[] = [
- { key: "manual", label: t("masteryPath.tabManual") },
- { key: "book", label: t("masteryPath.tabBook") },
- { key: "notebook", label: t("masteryPath.tabNotebook") },
- ];
-
- const submitDisabled =
- submitting ||
- (source === "book" && (!selectedBookId || bookChapters.length === 0)) ||
- (source === "notebook" && selectedRecordIds.size === 0);
-
- return (
- <div className="fixed inset-0 z-50 flex items-center justify-center">
- <div
- className="absolute inset-0 bg-black/40 backdrop-blur-sm"
- onClick={handleClose}
- />
- <div className="relative z-10 flex max-h-[80vh] w-full max-w-lg flex-col rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-xl">
- {/* Header */}
- <div className="flex items-center justify-between border-b border-[var(--border)] px-5 py-4">
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
- {t("masteryPath.createModule")}
- </h2>
- <button
- onClick={handleClose}
- className="rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--secondary)] hover:text-[var(--foreground)]"
- >
- <X className="h-4 w-4" />
- </button>
- </div>
-
- {/* Source picker */}
- <div className="flex gap-1 border-b border-[var(--border)] px-5 pt-3">
- {sources.map((s) => (
- <button
- key={s.key}
- onClick={() => {
- setSource(s.key);
- setError(null);
- }}
- className={`-mb-px rounded-t-md border-b-2 px-3 py-1.5 text-xs font-medium transition-colors ${
- source === s.key
- ? "border-[var(--primary)] bg-[var(--secondary)]/40 text-[var(--foreground)]"
- : "border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {s.label}
- </button>
- ))}
- </div>
-
- {/* Body */}
- <div className="flex-1 overflow-y-auto px-5 py-4">
- {error && (
- <div className="mb-3 rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-xs text-red-500">
- {error}
- </div>
- )}
-
- {source === "manual" && (
- <div className="space-y-4">
- <div>
- <label className="mb-1 block text-xs font-medium text-[var(--muted-foreground)]">
- {t("masteryPath.moduleName")}
- </label>
- <input
- value={moduleName}
- onChange={(e) => setModuleName(e.target.value)}
- placeholder={t("masteryPath.moduleNamePlaceholder")}
- className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none"
- />
- </div>
- <div>
- <label className="mb-2 block text-xs font-medium text-[var(--muted-foreground)]">
- {t("masteryPath.knowledgePointsLabel")}
- </label>
- {kpRows.map((row, i) => (
- <div key={i} className="mb-2 flex items-center gap-2">
- <input
- value={row.name}
- onChange={(e) => {
- const next = [...kpRows];
- next[i] = { ...next[i], name: e.target.value };
- setKpRows(next);
- }}
- placeholder={t("masteryPath.kpNamePlaceholder")}
- className="flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none"
- />
- <select
- value={row.type}
- onChange={(e) => {
- const next = [...kpRows];
- next[i] = { ...next[i], type: e.target.value };
- setKpRows(next);
- }}
- className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] focus:outline-none"
- >
- <option value="memory">
- {t("knowledgeType.memory")}
- </option>
- <option value="concept">
- {t("knowledgeType.concept")}
- </option>
- <option value="procedure">
- {t("knowledgeType.procedure")}
- </option>
- <option value="design">
- {t("knowledgeType.design")}
- </option>
- </select>
- {kpRows.length > 1 && (
- <button
- onClick={() =>
- setKpRows(kpRows.filter((_, j) => j !== i))
- }
- className="p-1 text-[var(--muted-foreground)] hover:text-red-500"
- >
- <Trash2 className="h-3.5 w-3.5" />
- </button>
- )}
- </div>
- ))}
- <button
- onClick={() =>
- setKpRows([...kpRows, { name: "", type: "concept" }])
- }
- className="flex items-center gap-1 text-xs text-[var(--primary)] hover:opacity-80"
- >
- <Plus className="h-3 w-3" />
- {t("masteryPath.addKp")}
- </button>
- </div>
- </div>
- )}
-
- {source === "book" && (
- <div className="space-y-3">
- {loadingBooks ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : books.length === 0 ? (
- <div className="py-8 text-center text-sm text-[var(--muted-foreground)]">
- {t("masteryPath.noBooks")}
- </div>
- ) : (
- <>
- <div className="max-h-40 space-y-1 overflow-y-auto">
- {books.map((book) => (
- <button
- key={book.id}
- onClick={() => setSelectedBookId(book.id)}
- className={`w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
- selectedBookId === book.id
- ? "border border-[var(--primary)]/30 bg-[var(--primary)]/10 text-[var(--foreground)]"
- : "border border-transparent text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
- }`}
- >
- <div className="truncate font-medium">
- {book.title || book.id}
- </div>
- <div className="text-xs opacity-70">
- {book.chapter_count ?? 0} {t("masteryPath.chapters")}{" "}
- · {book.status}
- </div>
- </button>
- ))}
- </div>
- {selectedBookId && (
- <div className="border-t border-[var(--border)] pt-3">
- {loadingChapters ? (
- <div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
- <Loader2 className="h-4 w-4 animate-spin" />
- {t("masteryPath.loadingChapters")}
- </div>
- ) : bookChapters.length === 0 ? (
- <div className="text-sm text-[var(--muted-foreground)]">
- {t("masteryPath.noChapters")}
- </div>
- ) : (
- <div>
- <p className="mb-2 text-xs font-medium text-[var(--muted-foreground)]">
- {t("masteryPath.chaptersToImport", {
- count: bookChapters.length,
- })}
- </p>
- <div className="max-h-32 space-y-1 overflow-y-auto">
- {bookChapters.map((ch, i) => (
- <div
- key={i}
- className="flex items-center gap-2 text-xs text-[var(--muted-foreground)]"
- >
- <FileText className="h-3 w-3 shrink-0" />
- <span className="truncate">{ch.title}</span>
- <span className="opacity-50">
- ({(ch.learning_objectives ?? []).length}{" "}
- {t("masteryPath.kps")})
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
- </>
- )}
- </div>
- )}
-
- {source === "notebook" && (
- <div className="space-y-3">
- {loadingNotebooks ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : notebooks.length === 0 ? (
- <div className="py-8 text-center text-sm text-[var(--muted-foreground)]">
- {t("masteryPath.noNotebooks")}
- </div>
- ) : (
- <>
- <div className="max-h-32 space-y-1 overflow-y-auto">
- {notebooks.map((nb) => (
- <button
- key={nb.id}
- onClick={() => setSelectedNotebook(nb.id)}
- className={`w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
- selectedNotebook === nb.id
- ? "border border-[var(--primary)]/30 bg-[var(--primary)]/10 text-[var(--foreground)]"
- : "border border-transparent text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
- }`}
- >
- <div className="truncate font-medium">{nb.name}</div>
- <div className="text-xs opacity-70">
- {nb.record_count ?? 0} {t("masteryPath.records")}
- </div>
- </button>
- ))}
- </div>
- {selectedNotebook && (
- <div className="border-t border-[var(--border)] pt-3">
- {loadingRecords ? (
- <div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
- <Loader2 className="h-4 w-4 animate-spin" />
- {t("masteryPath.loadingRecords")}
- </div>
- ) : notebookRecords.length === 0 ? (
- <div className="text-sm text-[var(--muted-foreground)]">
- {t("masteryPath.noRecords")}
- </div>
- ) : (
- <div>
- <p className="mb-2 text-xs font-medium text-[var(--muted-foreground)]">
- {t("masteryPath.selectRecords")} (
- {selectedRecordIds.size} {t("masteryPath.selected")}
- )
- </p>
- <div className="max-h-40 space-y-1 overflow-y-auto">
- {notebookRecords.slice(0, 20).map((rec) => (
- <label
- key={rec.id}
- className="flex cursor-pointer items-start gap-2 rounded px-2 py-1.5 text-xs hover:bg-[var(--secondary)]/40"
- >
- <input
- type="checkbox"
- checked={selectedRecordIds.has(rec.id)}
- onChange={(e) => {
- const next = new Set(selectedRecordIds);
- if (e.target.checked) next.add(rec.id);
- else next.delete(rec.id);
- setSelectedRecordIds(next);
- }}
- className="mt-0.5 rounded border-[var(--border)]"
- />
- <div className="min-w-0">
- <div className="truncate font-medium text-[var(--foreground)]">
- {rec.title || rec.id}
- </div>
- {rec.output && (
- <div className="truncate text-[var(--muted-foreground)] opacity-70">
- {rec.output.slice(0, 80)}
- </div>
- )}
- </div>
- </label>
- ))}
- </div>
- {notebookRecords.length > 20 && (
- <p className="mt-1 text-[10px] text-[var(--muted-foreground)] opacity-60">
- {t("masteryPath.recordsLimited")}
- </p>
- )}
- </div>
- )}
- </div>
- )}
- </>
- )}
- </div>
- )}
- </div>
-
- {/* Footer */}
- <div className="flex items-center justify-end gap-2 border-t border-[var(--border)] px-5 py-3">
- <button
- onClick={handleClose}
- className="rounded-lg border border-[var(--border)] px-4 py-1.5 text-sm text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
- >
- {t("masteryPath.cancel")}
- </button>
- <button
- onClick={() => void handleSubmit()}
- disabled={submitDisabled}
- className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-1.5 text-sm text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
- >
- {submitting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {source === "notebook"
- ? t("masteryPath.generateModules")
- : t("masteryPath.create")}
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/web/components/learning/ModuleTree.tsx b/web/components/learning/ModuleTree.tsx
deleted file mode 100644
index 2a60b9765..000000000
--- a/web/components/learning/ModuleTree.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-"use client";
-
-import { useState, useEffect } from "react";
-import { ChevronRight, ChevronDown, Circle } from "lucide-react";
-import { useTranslation } from "react-i18next";
-
-interface KnowledgePoint {
- id: string;
- name: string;
- type: string;
-}
-
-interface Module {
- id: string;
- name: string;
- order: number;
- knowledge_points: KnowledgePoint[];
- pass_threshold: number;
-}
-
-interface ModuleTreeProps {
- modules: Module[];
- masteryLevels: Record<string, number>;
- currentModuleId: string;
- onModuleClick?: (moduleId: string) => void;
-}
-
-function masteryColor(mastery: number, threshold: number): string {
- if (mastery >= threshold) return "text-green-500";
- if (mastery > 0) return "text-yellow-500";
- return "text-[var(--muted-foreground)]";
-}
-
-function ModuleNode({
- module,
- masteryLevels,
- isCurrent,
- onSelect,
-}: {
- module: Module;
- masteryLevels: Record<string, number>;
- isCurrent: boolean;
- onSelect?: () => void;
-}) {
- const [expanded, setExpanded] = useState(isCurrent);
-
- useEffect(() => {
- if (!isCurrent) return;
- const timer = setTimeout(() => setExpanded(true), 0);
- return () => clearTimeout(timer);
- }, [isCurrent]);
-
- const total = module.knowledge_points.length;
- const averageMastery =
- total > 0
- ? module.knowledge_points.reduce(
- (sum, kp) => sum + (masteryLevels[kp.id] ?? 0),
- 0,
- ) / total
- : 0;
- const masteryPercent = Math.round(averageMastery * 100);
-
- return (
- <div>
- <button
- onClick={() => {
- if (!isCurrent) onSelect?.();
- setExpanded((prev) => !prev);
- }}
- className={`flex items-center gap-1.5 w-full px-2 py-1.5 text-left text-sm rounded-md transition-colors cursor-pointer ${
- isCurrent
- ? "bg-[var(--primary)]/10 ring-1 ring-[var(--primary)]/30 text-[var(--primary)]"
- : "text-[var(--foreground)] hover:bg-[var(--accent)]"
- }`}
- >
- {expanded ? (
- <ChevronDown className="w-3.5 h-3.5 shrink-0" />
- ) : (
- <ChevronRight className="w-3.5 h-3.5 shrink-0" />
- )}
- <span className="truncate flex-1">{module.name}</span>
- <span className="text-xs text-[var(--muted-foreground)] shrink-0">
- {masteryPercent}%
- </span>
- </button>
- {expanded && (
- <div className="ml-4 border-l border-[var(--border)] pl-2">
- {module.knowledge_points.map((kp) => {
- const mastery = masteryLevels[kp.id] ?? 0;
- return (
- <div
- key={kp.id}
- className="flex items-center gap-1.5 px-2 py-1 text-sm text-[var(--muted-foreground)]"
- >
- <Circle
- className={`w-2 h-2 shrink-0 fill-current ${masteryColor(mastery, module.pass_threshold)}`}
- />
- <span className="truncate">{kp.name}</span>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-}
-
-export default function ModuleTree({
- modules,
- masteryLevels,
- currentModuleId,
- onModuleClick,
-}: ModuleTreeProps) {
- const { t } = useTranslation();
- const sorted = [...modules].sort((a, b) => a.order - b.order);
-
- if (sorted.length === 0) {
- return (
- <div className="text-sm text-[var(--muted-foreground)] px-2 py-1">
- {t("masteryPath.noModulesLoaded")}
- </div>
- );
- }
-
- return (
- <div className="space-y-0.5">
- {sorted.map((mod) => (
- <ModuleNode
- key={mod.id}
- module={mod}
- masteryLevels={masteryLevels}
- isCurrent={mod.id === currentModuleId}
- onSelect={() => onModuleClick?.(mod.id)}
- />
- ))}
- </div>
- );
-}
diff --git a/web/components/learning/StageContent.tsx b/web/components/learning/StageContent.tsx
deleted file mode 100644
index 7183a9528..000000000
--- a/web/components/learning/StageContent.tsx
+++ /dev/null
@@ -1,215 +0,0 @@
-"use client";
-
-import { useTranslation } from "react-i18next";
-import MarkdownRenderer from "@/components/common/MarkdownRenderer";
-
-/* ------------------------------------------------------------------ */
-/* Quiz payload parsing */
-/* ------------------------------------------------------------------ */
-
-type JsonObject = Record<string, unknown>;
-
-export interface QuizQuestion {
- /** Stable id for the question, if the server provided one. */
- questionId?: string;
- /** The full (answer-stripped) question object as sent by the backend. */
- fields: JsonObject;
- /** Multiple-choice options, if present. */
- options: string[];
-}
-
-/** One parsed segment of a stage's streamed content. */
-export type StageSegment =
- | { kind: "markdown"; text: string }
- | { kind: "quiz"; question: QuizQuestion };
-
-function isJsonObject(value: unknown): value is JsonObject {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
-function tryParseJson(text: string): unknown {
- try {
- return JSON.parse(text);
- } catch {
- return undefined;
- }
-}
-
-function toText(value: unknown): string {
- if (value == null) return "";
- if (typeof value === "string") return value;
- if (typeof value === "number" || typeof value === "boolean")
- return String(value);
- if (Array.isArray(value)) return value.map(toText).join(", ");
- return JSON.stringify(value);
-}
-
-function normalizeOptions(raw: unknown): string[] {
- if (!Array.isArray(raw)) return [];
- return raw.map((opt) => {
- if (isJsonObject(opt)) {
- // Common shapes: {label, text} / {key, value} / {id, content}
- const label = opt.label ?? opt.key ?? opt.id;
- const body = opt.text ?? opt.value ?? opt.content ?? opt.option;
- if (label != null && body != null)
- return `${toText(label)}. ${toText(body)}`;
- return toText(body ?? label ?? opt);
- }
- return toText(opt);
- });
-}
-
-function parseQuestionPayload(obj: JsonObject): QuizQuestion {
- const inner = isJsonObject(obj.question) ? obj.question : obj;
- const questionId =
- typeof obj.question_id === "string" ? obj.question_id : undefined;
- return {
- questionId,
- fields: inner,
- options: normalizeOptions(inner.options),
- };
-}
-
-/**
- * Split a stage's accumulated content into ordered markdown / quiz segments.
- * Quiz questions arrive as standalone JSON lines ({question, question_id});
- * everything else is plain markdown (which may contain LaTeX).
- */
-export function parseStageContent(content: string): StageSegment[] {
- const segments: StageSegment[] = [];
- let markdownBuffer: string[] = [];
-
- const flush = () => {
- const text = markdownBuffer.join("\n").trim();
- if (text) segments.push({ kind: "markdown", text });
- markdownBuffer = [];
- };
-
- for (const line of content.split("\n")) {
- const trimmed = line.trim();
- // A quiz line is a self-contained JSON object carrying a question.
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
- const parsed = tryParseJson(trimmed);
- if (
- isJsonObject(parsed) &&
- ("question" in parsed || "question_id" in parsed)
- ) {
- flush();
- segments.push({ kind: "quiz", question: parseQuestionPayload(parsed) });
- continue;
- }
- }
- markdownBuffer.push(line);
- }
- flush();
- return segments;
-}
-
-/** The question the answer input should bind to (last one in the stream). */
-export function activeQuestion(content: string): QuizQuestion | null {
- const segments = parseStageContent(content);
- for (let i = segments.length - 1; i >= 0; i -= 1) {
- const seg = segments[i];
- if (seg.kind === "quiz") return seg.question;
- }
- return null;
-}
-
-/* ------------------------------------------------------------------ */
-/* Rendering */
-/* ------------------------------------------------------------------ */
-
-const HIDDEN_FIELDS = new Set([
- "answer",
- "correct_answer",
- "solution",
- "options",
- "question_id",
- "id",
-]);
-
-function QuestionText({ question }: { question: QuizQuestion }) {
- const { fields } = question;
- const prompt = fields.question ?? fields.text ?? fields.prompt ?? fields.stem;
- if (prompt != null) {
- return (
- <MarkdownRenderer content={toText(prompt)} enableMath variant="compact" />
- );
- }
- // Fallback: render any descriptive fields we didn't hide.
- const entries = Object.entries(fields).filter(([k]) => !HIDDEN_FIELDS.has(k));
- return (
- <div className="space-y-1">
- {entries.map(([key, value]) => (
- <div key={key} className="text-sm text-[var(--foreground)]">
- <span className="text-[var(--muted-foreground)]">{key}: </span>
- {toText(value)}
- </div>
- ))}
- </div>
- );
-}
-
-function QuizCard({
- question,
- index,
-}: {
- question: QuizQuestion;
- index: number;
-}) {
- const { t } = useTranslation();
- return (
- <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
- <div className="mb-2 flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
- <span className="flex h-5 w-5 items-center justify-center rounded-full bg-[var(--primary)]/10 text-[var(--primary)]">
- {index + 1}
- </span>
- <span>{t("masteryPath.question")}</span>
- </div>
- <QuestionText question={question} />
- {question.options.length > 0 && (
- <ul className="mt-3 space-y-1.5">
- {question.options.map((opt, i) => (
- <li
- key={i}
- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)]"
- >
- {opt}
- </li>
- ))}
- </ul>
- )}
- </div>
- );
-}
-
-export function StageContent({ content }: { content: string }) {
- const segments = parseStageContent(content);
- // Precompute the running quiz number per segment so render stays pure
- // (no mutable counter reassigned inside the JSX map).
- const quizNumbers = segments.map((seg, i) =>
- seg.kind === "quiz"
- ? segments.slice(0, i).filter((s) => s.kind === "quiz").length
- : -1,
- );
- return (
- <div className="space-y-4">
- {segments.map((seg, i) => {
- if (seg.kind === "markdown") {
- return (
- <MarkdownRenderer
- key={i}
- content={seg.text}
- enableMath
- enableCode
- enableMermaid
- />
- );
- }
- return (
- <QuizCard key={i} question={seg.question} index={quizNumbers[i]} />
- );
- })}
- </div>
- );
-}
diff --git a/web/components/learning/StageRoadmap.tsx b/web/components/learning/StageRoadmap.tsx
deleted file mode 100644
index 5c2b78e5d..000000000
--- a/web/components/learning/StageRoadmap.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-"use client";
-
-import { Check, Loader2 } from "lucide-react";
-import { useTranslation } from "react-i18next";
-import { MASTERY_STAGES, type StageProgress } from "@/hooks/useMasteryTurn";
-
-interface StageRoadmapProps {
- stages: StageProgress[];
- currentStage: string;
-}
-
-type DisplayStatus = "done" | "active" | "upcoming";
-
-/**
- * The fixed 6-stage journey, decorated with live status. The per-knowledge
- * point loop (explain ↔ feynman_check) repeats internally; the roadmap only
- * presents the canonical sequence so the learner sees the whole path.
- */
-export default function StageRoadmap({
- stages,
- currentStage,
-}: StageRoadmapProps) {
- const { t } = useTranslation();
-
- const statusFor = (stage: string): DisplayStatus => {
- if (stage === currentStage) return "active";
- const seen = stages.find((s) => s.stage === stage);
- if (seen?.status === "completed") return "done";
- return "upcoming";
- };
-
- return (
- <ol className="space-y-0.5">
- {MASTERY_STAGES.map((stage, i) => {
- const status = statusFor(stage);
- return (
- <li key={stage} className="flex items-center gap-2.5 py-1">
- <span
- className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[11px] font-medium ${
- status === "done"
- ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
- : status === "active"
- ? "bg-[var(--primary)]/15 text-[var(--primary)] ring-1 ring-[var(--primary)]/40"
- : "bg-[var(--muted)] text-[var(--muted-foreground)]"
- }`}
- >
- {status === "done" ? (
- <Check className="h-3 w-3" strokeWidth={2.5} />
- ) : status === "active" ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- i + 1
- )}
- </span>
- <span
- className={`text-[13px] ${
- status === "active"
- ? "font-medium text-[var(--foreground)]"
- : status === "done"
- ? "text-[var(--foreground)]"
- : "text-[var(--muted-foreground)]"
- }`}
- >
- {t(`masteryPath.stage.${stage}`)}
- </span>
- </li>
- );
- })}
- </ol>
- );
-}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 7963f5b78..461ff9b99 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -11,6 +11,7 @@ import {
Brain,
ChevronDown,
Github,
+ GraduationCap,
HeartHandshake,
LayoutGrid,
Library,
@@ -60,9 +61,12 @@ const PRIMARY_NAV: NavEntry[] = [
icon: BookOpen,
tooltipKey: "Knowledge tooltip",
},
- // Mastery Path (/learning) is hidden from the product nav for now — the
- // route, its components and the backend stay in place so the feature can
- // be reworked and re-surfaced later. Re-add this entry to bring it back.
+ {
+ href: "/learning",
+ label: "Mastery Path",
+ icon: GraduationCap,
+ tooltipKey: "Mastery Path tooltip",
+ },
{
href: "/space",
label: "Space",
diff --git a/web/hooks/useMasteryTurn.ts b/web/hooks/useMasteryTurn.ts
deleted file mode 100644
index 5b849eb50..000000000
--- a/web/hooks/useMasteryTurn.ts
+++ /dev/null
@@ -1,480 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useReducer, useRef } from "react";
-import { wsUrl } from "@/lib/api";
-
-/* ------------------------------------------------------------------ */
-/* Protocol types */
-/* ------------------------------------------------------------------ */
-
-/** A single event coming over the unified turn-runtime WebSocket. */
-export interface MasteryStreamEvent {
- type: string;
- source?: string;
- stage?: string;
- content?: string;
- metadata?: Record<string, unknown>;
- turn_id?: string;
- // Some event types carry extra top-level fields:
- status?: string;
- success?: boolean;
- module_id?: string;
-}
-
-export const MASTERY_CAPABILITY = "mastery_path";
-
-/** The canonical journey, in display order. Terminal "completed" is separate. */
-export const MASTERY_STAGES = [
- "diagnostic",
- "explain",
- "feynman_check",
- "practice",
- "error_diagnosis",
- "review",
-] as const;
-
-export type StageStatus = "pending" | "active" | "completed" | "error";
-
-export interface StageProgress {
- stage: string;
- status: StageStatus;
- content: string;
-}
-
-/* ------------------------------------------------------------------ */
-/* Reducer — single source of truth for session state */
-/* ------------------------------------------------------------------ */
-
-export interface MasteryState {
- /** Live record of every stage we've seen this session, in arrival order. */
- stages: StageProgress[];
- /** Stage currently streaming content (empty when none is active). */
- currentStage: string;
- /** Socket is connecting / reconnecting. */
- connecting: boolean;
- /** A turn is running and we're waiting on the model (no input yet). */
- busy: boolean;
- /** The model asked the learner for an answer. */
- waitingForInput: boolean;
- /** Prompt to show above the answer input. */
- inputPrompt: string;
- /** Set true once a turn finishes (`done`) and the terminal stage isn't reached. */
- canContinue: boolean;
- /** The terminal "completed" stage was reached. */
- completed: boolean;
- /** One error banner, or null. */
- error: string | null;
- /** Current turn id (needed for user_input). */
- turnId: string;
-}
-
-type Action =
- | { type: "CONNECTING" }
- | { type: "OPEN" }
- | { type: "TURN_ID"; turnId: string }
- | { type: "BUSY" }
- | { type: "WAIT_FOR_INPUT"; prompt: string }
- | { type: "STAGE_START"; stage: string }
- | { type: "CONTENT"; content: string }
- | { type: "STAGE_END" }
- | { type: "DONE" }
- | { type: "ERROR"; message: string }
- | { type: "CLEAR_ERROR" }
- | { type: "RESET" };
-
-const initialState: MasteryState = {
- stages: [],
- currentStage: "",
- connecting: true,
- busy: false,
- waitingForInput: false,
- inputPrompt: "",
- canContinue: false,
- completed: false,
- error: null,
- turnId: "",
-};
-
-function reducer(state: MasteryState, action: Action): MasteryState {
- switch (action.type) {
- case "CONNECTING":
- return { ...state, connecting: true };
- case "OPEN":
- return { ...state, connecting: false, error: null };
- case "TURN_ID":
- return state.turnId === action.turnId
- ? state
- : { ...state, turnId: action.turnId };
- case "BUSY":
- return { ...state, busy: true, canContinue: false };
- case "WAIT_FOR_INPUT":
- return {
- ...state,
- busy: false,
- waitingForInput: true,
- inputPrompt: action.prompt,
- };
- case "STAGE_START": {
- const idx = state.stages.findIndex((s) => s.stage === action.stage);
- const stages =
- idx >= 0
- ? state.stages.map((s, i) =>
- i === idx ? { ...s, status: "active" as const, content: "" } : s,
- )
- : [
- ...state.stages,
- { stage: action.stage, status: "active" as const, content: "" },
- ];
- return {
- ...state,
- stages,
- currentStage: action.stage,
- busy: false,
- canContinue: false,
- waitingForInput: false,
- error: null,
- };
- }
- case "CONTENT": {
- if (!state.currentStage) return state;
- const stages = state.stages.map((s) =>
- s.stage === state.currentStage
- ? {
- ...s,
- content: s.content
- ? `${s.content}\n${action.content}`
- : action.content,
- }
- : s,
- );
- return { ...state, stages };
- }
- case "STAGE_END": {
- const ended = state.currentStage;
- if (!ended) return state;
- const stages = state.stages.map((s) =>
- s.stage === ended ? { ...s, status: "completed" as const } : s,
- );
- return {
- ...state,
- stages,
- currentStage: "",
- completed: state.completed || ended === "completed",
- };
- }
- case "DONE": {
- const reachedTerminal =
- state.completed ||
- state.stages.some(
- (s) => s.stage === "completed" && s.status === "completed",
- );
- return {
- ...state,
- busy: false,
- waitingForInput: false,
- completed: reachedTerminal,
- // Surface a Continue affordance only when not terminal and no error.
- canContinue: !reachedTerminal && !state.error,
- };
- }
- case "ERROR": {
- const stages = state.currentStage
- ? state.stages.map((s) =>
- s.stage === state.currentStage
- ? { ...s, status: "error" as const }
- : s,
- )
- : state.stages;
- return {
- ...state,
- stages,
- busy: false,
- waitingForInput: false,
- canContinue: false,
- error: action.message,
- };
- }
- case "CLEAR_ERROR":
- return { ...state, error: null };
- case "RESET":
- return { ...initialState, connecting: true };
- default:
- return state;
- }
-}
-
-/* ------------------------------------------------------------------ */
-/* Hook */
-/* ------------------------------------------------------------------ */
-
-interface UseMasteryTurnOptions {
- sessionId: string;
- /** Gate connecting until the caller has resolved which module to learn. */
- enabled: boolean;
- /** Called after a stage ends, so the caller can refetch mastery/progress. */
- onStageEnd?: (stage: string) => void;
- /** Called when the server confirms a module switch. */
- onModuleChanged?: (moduleId: string, success: boolean) => void;
-}
-
-const MAX_RECONNECT_ATTEMPTS = 5;
-
-export interface UseMasteryTurnResult extends MasteryState {
- /** Force a (re)connect; resets the reconnect backoff counter. */
- reconnect: () => void;
- /** Advance to the next turn after a `done`. */
- continueTurn: () => void;
- /** Submit the learner's answer to the current waiting prompt. */
- submitAnswer: (text: string) => void;
- /** Switch the active module mid-session. */
- changeModule: (moduleId: string) => void;
-}
-
-export function useMasteryTurn({
- sessionId,
- enabled,
- onStageEnd,
- onModuleChanged,
-}: UseMasteryTurnOptions): UseMasteryTurnResult {
- const [state, dispatch] = useReducer(reducer, initialState);
-
- const wsRef = useRef<WebSocket | null>(null);
- const turnIdRef = useRef<string>("");
- const reconnectAttemptsRef = useRef(0);
- const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const intentionalCloseRef = useRef(false);
- const connectRef = useRef<() => void>(() => {});
-
- // Suppress the "cancelled" error that the server emits right after a
- // module switch cancels the in-flight turn.
- const moduleSwitchRef = useRef(false);
-
- // Keep callbacks fresh without re-subscribing the socket.
- const onStageEndRef = useRef(onStageEnd);
- const onModuleChangedRef = useRef(onModuleChanged);
- useEffect(() => {
- onStageEndRef.current = onStageEnd;
- onModuleChangedRef.current = onModuleChanged;
- }, [onStageEnd, onModuleChanged]);
-
- const send = useCallback((payload: Record<string, unknown>) => {
- const ws = wsRef.current;
- if (ws?.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify(payload));
- return true;
- }
- return false;
- }, []);
-
- const startTurn = useCallback(
- (content: string) => {
- send({
- type: "start_turn",
- session_id: sessionId,
- capability: MASTERY_CAPABILITY,
- content,
- book_references: [{ book_id: sessionId, page_ids: [] }],
- config: {},
- });
- dispatch({ type: "BUSY" });
- },
- [send, sessionId],
- );
-
- const handleEvent = useCallback(
- (evt: MasteryStreamEvent) => {
- if (evt.turn_id) {
- turnIdRef.current = evt.turn_id;
- dispatch({ type: "TURN_ID", turnId: evt.turn_id });
- }
-
- switch (evt.type) {
- case "active_turn_info": {
- if (evt.turn_id && evt.status === "running") {
- turnIdRef.current = evt.turn_id;
- send({ type: "subscribe_turn", turn_id: evt.turn_id });
- dispatch({ type: "BUSY" });
- } else {
- startTurn("Start learning");
- }
- break;
- }
- case "wait_for_input":
- dispatch({
- type: "WAIT_FOR_INPUT",
- prompt: evt.content || "Please enter your answer",
- });
- break;
- case "stage_start":
- moduleSwitchRef.current = false;
- dispatch({ type: "STAGE_START", stage: evt.stage || "" });
- break;
- case "content":
- if (evt.content) dispatch({ type: "CONTENT", content: evt.content });
- break;
- case "result":
- case "stage_end": {
- const ended = evt.stage;
- dispatch({ type: "STAGE_END" });
- if (ended) onStageEndRef.current?.(ended);
- break;
- }
- case "done":
- moduleSwitchRef.current = false;
- dispatch({ type: "DONE" });
- break;
- case "module_changed": {
- moduleSwitchRef.current = true;
- dispatch({ type: "CLEAR_ERROR" });
- if (evt.success !== false && evt.module_id) {
- onModuleChangedRef.current?.(evt.module_id, true);
- } else {
- onModuleChangedRef.current?.(evt.module_id || "", false);
- }
- break;
- }
- case "error": {
- // Ignore the cancellation error emitted right after a module switch.
- if (moduleSwitchRef.current && evt.content?.includes("cancelled")) {
- return;
- }
- dispatch({
- type: "ERROR",
- message: evt.content || "An error occurred",
- });
- break;
- }
- default:
- break;
- }
- },
- [send, startTurn],
- );
-
- const handleEventRef = useRef(handleEvent);
- useEffect(() => {
- handleEventRef.current = handleEvent;
- }, [handleEvent]);
-
- const connect = useCallback(() => {
- if (!enabled) return;
- const existing = wsRef.current;
- if (
- existing?.readyState === WebSocket.OPEN ||
- existing?.readyState === WebSocket.CONNECTING
- ) {
- return;
- }
- if (reconnectTimerRef.current) {
- clearTimeout(reconnectTimerRef.current);
- reconnectTimerRef.current = null;
- }
- intentionalCloseRef.current = false;
- dispatch({ type: "CONNECTING" });
-
- const ws = new WebSocket(wsUrl("/api/v1/ws"));
- wsRef.current = ws;
-
- ws.onopen = () => {
- reconnectAttemptsRef.current = 0;
- dispatch({ type: "OPEN" });
- // Resume an in-flight turn if one exists; otherwise the response
- // (active_turn_info) starts a fresh turn.
- ws.send(
- JSON.stringify({ type: "check_active_turn", session_id: sessionId }),
- );
- };
-
- ws.onmessage = (event) => {
- try {
- const evt = JSON.parse(event.data) as MasteryStreamEvent;
- handleEventRef.current(evt);
- } catch {
- // Ignore malformed frames.
- }
- };
-
- ws.onerror = () => {
- // onclose fires next and drives reconnect; avoid double-handling here.
- };
-
- ws.onclose = () => {
- if (intentionalCloseRef.current) return;
- if (reconnectAttemptsRef.current < MAX_RECONNECT_ATTEMPTS) {
- const delay = Math.min(1000 * 2 ** reconnectAttemptsRef.current, 10000);
- reconnectAttemptsRef.current += 1;
- dispatch({ type: "CONNECTING" });
- reconnectTimerRef.current = setTimeout(
- () => connectRef.current(),
- delay,
- );
- } else {
- dispatch({ type: "ERROR", message: "Connection lost" });
- }
- };
- }, [enabled, sessionId]);
-
- useEffect(() => {
- connectRef.current = connect;
- }, [connect]);
-
- // Connect / teardown on mount + when `enabled`/session changes.
- useEffect(() => {
- if (!enabled) return;
- const timer = setTimeout(() => connect(), 0);
- return () => {
- clearTimeout(timer);
- intentionalCloseRef.current = true;
- if (reconnectTimerRef.current) {
- clearTimeout(reconnectTimerRef.current);
- reconnectTimerRef.current = null;
- }
- wsRef.current?.close();
- wsRef.current = null;
- };
- }, [connect, enabled]);
-
- const reconnect = useCallback(() => {
- reconnectAttemptsRef.current = 0;
- dispatch({ type: "CLEAR_ERROR" });
- connect();
- }, [connect]);
-
- const continueTurn = useCallback(() => {
- dispatch({ type: "CLEAR_ERROR" });
- startTurn("Continue");
- }, [startTurn]);
-
- const submitAnswer = useCallback(
- (text: string) => {
- if (!turnIdRef.current) return;
- const ok = send({
- type: "user_input",
- turn_id: turnIdRef.current,
- content: text,
- });
- if (ok) dispatch({ type: "BUSY" });
- },
- [send],
- );
-
- const changeModule = useCallback(
- (moduleId: string) => {
- moduleSwitchRef.current = true;
- send({
- type: "change_module",
- session_id: sessionId,
- module_id: moduleId,
- });
- },
- [send, sessionId],
- );
-
- return {
- ...state,
- reconnect,
- continueTurn,
- submitAnswer,
- changeModule,
- };
-}
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 933ba4a71..5fed98661 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -55,6 +55,59 @@ export async function initModules(bookId: string, modules: ModuleInit[]) {
return res.json();
}
+// ── Mastery map (the dashboard view) ──────────────────────────────────────
+// Mirrors deeptutor/learning/policy.py map_summary + next_objective.
+
+export type ObjectiveStatus = "new" | "learning" | "mastered";
+
+export interface MapKnowledgePoint {
+ id: string;
+ name: string;
+ type: string;
+ status: ObjectiveStatus;
+ mastery: number;
+}
+
+export interface MapModule {
+ id: string;
+ name: string;
+ order: number;
+ mastered: number;
+ total: number;
+ knowledge_points: MapKnowledgePoint[];
+}
+
+export interface MasteryMap {
+ counts: { mastered: number; learning: number; new: number; total: number };
+ due_reviews: number;
+ complete: boolean;
+ modules: MapModule[];
+}
+
+export interface NextStep {
+ action: string;
+ knowledge_point_name: string;
+ knowledge_point_type: string;
+ status: string;
+ mastery: number;
+ threshold: number;
+ reason: string;
+}
+
+export interface MasteryMapResult {
+ book_id: string;
+ next: NextStep;
+ map: MasteryMap;
+}
+
+export async function fetchMasteryMap(pathId: string): Promise<MasteryMapResult> {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/learning/progress/${encodeURIComponent(pathId)}/map`),
+ );
+ if (!res.ok) throw new Error(`Failed to fetch mastery map: ${res.status}`);
+ return res.json() as Promise<MasteryMapResult>;
+}
+
export interface ProgressSummary {
book_id: string;
name: string;
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 0ae80db43..d9bb0a49f 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2356,5 +2356,7 @@
"Please use the attached file(s).": "Please use the attached file(s).",
"This channel is not available on the server.": "This channel is not available on the server.",
"Partner": "Partner",
- "Edited — your version becomes this partner's soul. The original template is untouched.": "Edited — your version becomes this partner's soul. The original template is untouched."
+ "Edited — your version becomes this partner's soul. The original template is untouched.": "Edited — your version becomes this partner's soul. The original template is untouched.",
+ "Mastery-based tutoring with a hard gate": "Mastery-based tutoring with a hard gate",
+ "Mastery Path tooltip": "Mastery-based learning with a hard gate"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 86322727c..f94005888 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2356,5 +2356,7 @@
"Please use the attached file(s).": "请结合附件文件回答。",
"This channel is not available on the server.": "该频道在此服务器上不可用。",
"Partner": "伙伴",
- "Edited — your version becomes this partner's soul. The original template is untouched.": "已编辑——你的版本将成为这个伙伴的 soul,原模板保持不变。"
+ "Edited — your version becomes this partner's soul. The original template is untouched.": "已编辑——你的版本将成为这个伙伴的 soul,原模板保持不变。",
+ "Mastery-based tutoring with a hard gate": "掌握式辅导:硬门槛 + 间隔复习",
+ "Mastery Path tooltip": "掌握式学习:硬门槛与间隔复习"
}