DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): hand a topic's materials to the tutor that teaches it
Bingxi Zhao (Frank)d67fc1d515d0
diff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.mdindex 4bf99af20..7841444a2 100644--- a/deeptutor/capabilities/mastery/prompts/en/system.md+++ b/deeptutor/capabilities/mastery/prompts/en/system.md@@ -4,7 +4,7 @@ You are a one-on-one mastery tutor. The learner works through a map of objectiveFIRST 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).+- No objectives yet? Design a path from the learner's materials (use `rag` to search any attached knowledge base) 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. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. If `pending_interaction.status` is `answered`, immediately call `mastery_grade` with its persisted `learner_answer` and `question_id` instead of asking the learner twice. Otherwise present the pending question with `ask_user`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`. Always pass `explanation` to `mastery_quiz` (why the expected answer is right): it never appears on the card the learner is answering, but it travels with the attempt into their question bank, where it is the only explanation they will have when reviewing the mistake.- If the learner explicitly asks to abandon the current question (or it is unrecoverably stuck after retrying an `answered` grade), call `mastery_skip_question`, then continue the same objective with a different `mastery_quiz`. A skipped question gives no mastery credit and must never be used to pass a gate.@@ -16,4 +16,4 @@ A path outlives any one conversation. When the learner asks what they are studyiQuestions must discriminate: test whether the learner can tell things apart and apply them, never whether they can recite a definition back. Every distractor should encode a specific, plausible misconception, and match the correct option in length, specificity, and phrasing. **Never** hint at the answer — no "(Recommended)" markers on options, no writing the correct one longer or more complete than the rest, no ordering by correctness. This is an assessment, not a preference card.-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.+The materials the learner chose for this topic arrive as a `[Topic Materials]` manifest, and the parts relevant to this turn have already been read into context for you — teach from them rather than from memory. You cannot read rows marked `unavailable`: never describe or quote their contents; say plainly that the material is not readable and continue with what is. When the learner asks whether you can see their materials, answer from the manifest and name what you actually have — never a blanket "yes, I can see it". Keep each turn focused on one objective. Be warm and encouraging, but hold the bar — clearing the gate is the point, not moving fast.diff --git a/deeptutor/capabilities/mastery/prompts/zh/system.md b/deeptutor/capabilities/mastery/prompts/zh/system.mdindex 2fb44cda0..2acc8e8b4 100644--- a/deeptutor/capabilities/mastery/prompts/zh/system.md+++ b/deeptutor/capabilities/mastery/prompts/zh/system.md@@ -4,7 +4,7 @@每一轮都要先调用 `mastery_status`。它会返回当前要攻克的知识点、是否有待批改的作答、到期复习项,以及整张地图。请信任它来决定学什么——绝不要自己猜下一个知识点。然后针对该知识点行动:-- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。+- 还没有任何知识点?根据学习者的材料设计一条路径(有知识库时用 `rag` 检索),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。如果 `pending_interaction.status` 是 `answered`,应立即用其中持久化的 `learner_answer` 和 `question_id` 调用 `mastery_grade`,不要让学习者重复作答;否则再用 `ask_user` 展示待答题目。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。每次调用 `mastery_quiz` 都要带上 `explanation`(这个答案为什么对):它不会出现在作答卡片上,但会随作答记录进入学习者的题库,是他们日后复习错题时唯一能看到的解析。- 如果学习者明确要求放弃当前题目,或重试已提交 (`answered`) 的评分后仍无法恢复,调用 `mastery_skip_question`,然后继续同一知识点并另出一题。被跳过的题目不给任何掌握度,也绝不能用来越过门槛。@@ -16,4 +16,4 @@出题必须有区分度:考的是能否辨析与应用,而不是复述定义原话;每个干扰项都要对应一种具体的常见误解,并且与正确项在长度、具体程度、措辞风格上相当。**绝不**以任何方式暗示答案——不给选项加「(推荐)」这类标记,不把正确项写得更长更完整,也不按正确性排序。这是考核,不是选择偏好。-有材料时优先用学习者自己的材料来教。每一轮聚焦一个知识点。态度温暖鼓励,但守住门槛——目标是达成掌握,而非求快。+学习者为这个主题选定的材料以 `[Topic Materials]` 清单给出,与本轮相关的部分已由前置调查读入上下文——优先用它们来教,而不是凭记忆。清单里标 `unavailable` 的材料你读不到:绝不要描述或引用其内容,直接说明该材料读不到,再用可用的材料继续。学习者问「你能看到我的材料吗」时,照清单如实回答你实际拥有的部分,不要笼统地说「看得到」。每一轮聚焦一个知识点。态度温暖鼓励,但守住门槛——目标是达成掌握,而非求快。diff --git a/deeptutor/learning/tests/test_topic_materials.py b/deeptutor/learning/tests/test_topic_materials.pynew file mode 100644index 000000000..566a5fff2--- /dev/null+++ b/deeptutor/learning/tests/test_topic_materials.py@@ -0,0 +1,173 @@+"""A topic's materials must reach the tutor, and be honest when they cannot."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from deeptutor.learning.models import TopicSource, TopicSourceKind+from deeptutor.learning.topic_materials import (+ build_topic_materials,+ render_topic_manifest,+)+++class _FakeChapter(SimpleNamespace):+ pass+++def _book_storage(chapters: list[_FakeChapter]):+ return SimpleNamespace(+ load_book=lambda book_id: SimpleNamespace(title="Agentic RAG", id=book_id),+ load_spine=lambda book_id: SimpleNamespace(chapters=chapters),+ )+++def _chapter(cid: str, title: str, order: int, pages: list[str], summary: str = "") -> _FakeChapter:+ return _FakeChapter(+ id=cid,+ title=title,+ order=order,+ page_ids=pages,+ summary=summary,+ learning_objectives=[],+ )+++def _source(kind: TopicSourceKind, source_id: str, label: str, **kwargs) -> TopicSource:+ return TopicSource(+ id=f"source_{source_id or label}",+ kind=kind,+ source_id=source_id,+ label=label,+ **kwargs,+ )+++def two_chapter_book(monkeypatch: pytest.MonkeyPatch) -> None:+ chapters = [+ _chapter("ch_a", "Beyond the Linear Pipeline", 0, ["p1"], summary="Why static RAG fails."),+ _chapter("ch_b", "The Agent OS", 1, ["p2", "p3"]),+ ]+ monkeypatch.setattr(+ "deeptutor.book.storage.get_book_storage", lambda: _book_storage(chapters)+ )+ monkeypatch.setattr(+ "deeptutor.book.context.build_book_context",+ lambda refs, **kwargs: SimpleNamespace(+ text="CONTENT " + ",".join(refs[0]["page_ids"]), references=[], warnings=[]+ ),+ )+++def test_each_book_chapter_becomes_its_own_readable_source(two_chapter_book: None) -> None:+ """Per-chapter, not per-book: a whole book cannot be one tool result."""+ materials = build_topic_materials(+ [_source(TopicSourceKind.BOOK, "bk_1", "Agentic RAG")]+ )+ manifest, index = render_topic_manifest(materials)++ assert sorted(index) == ["bk-bk_1-ch_a", "bk-bk_1-ch_b"]+ assert index["bk-bk_1-ch_a"] == "CONTENT p1"+ assert index["bk-bk_1-ch_b"] == "CONTENT p2,p3"+ # The chapter's own summary is what lets the tutor pick a chapter without+ # reading all of them first.+ assert "Why static RAG fails." in manifest+ assert "1. Beyond the Linear Pipeline" in manifest+++def test_goal_source_is_not_offered_as_readable_material() -> None:+ """The goal is the objective, not something to 'read'."""+ materials = build_topic_materials(+ [_source(TopicSourceKind.GOAL, "", "Learning goal", excerpt="Master RAG")]+ )+ assert materials.is_empty()+ assert render_topic_manifest(materials) == ("", {})+++def test_knowledge_base_is_listed_as_searchable_but_never_readable() -> None:+ """A KB is searched with rag; listing it stops the tutor inventing it."""+ materials = build_topic_materials(+ [_source(TopicSourceKind.KNOWLEDGE_BASE, "mechanics-kb", "Mechanics KB")]+ )+ manifest, index = render_topic_manifest(materials)++ assert index == {}+ assert "search with rag" in manifest+ assert "mechanics-kb" in manifest+++def test_unavailable_material_is_named_rather_than_dropped() -> None:+ """Silently dropping it is what let the tutor claim it had read the book."""+ materials = build_topic_materials(+ [_source(TopicSourceKind.BOOK, "bk_gone", "Missing book", available=False)]+ )+ manifest, index = render_topic_manifest(materials)++ assert index == {}+ assert "unavailable" in manifest+ assert "Missing book" in manifest+ # The instruction that actually prevents the hallucination.+ assert "Never describe or quote their contents" in manifest+++def test_chapter_without_pages_is_listed_as_not_written_yet(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """'This chapter exists but is unwritten' is a fact the tutor must be able+ to state instead of inventing its contents."""+ chapters = [_chapter("ch_a", "Planned chapter", 0, [], summary="Coming soon.")]+ monkeypatch.setattr(+ "deeptutor.book.storage.get_book_storage", lambda: _book_storage(chapters)+ )+ materials = build_topic_materials([_source(TopicSourceKind.BOOK, "bk_1", "Agentic RAG")])+ manifest, index = render_topic_manifest(materials)++ assert index == {}+ assert "not written yet" in manifest+++def test_one_failing_material_never_takes_the_turn_down(+ monkeypatch: pytest.MonkeyPatch, two_chapter_book: None+) -> None:+ """Losing a material degrades the lesson; raising would end the turn."""++ def _explode() -> None:+ raise RuntimeError("notebook store is down")++ monkeypatch.setattr("deeptutor.services.notebook.get_notebook_manager", _explode)++ materials = build_topic_materials(+ [+ _source(TopicSourceKind.NOTEBOOK, "nb_1", "Broken notebook", position=0),+ _source(TopicSourceKind.BOOK, "bk_1", "Agentic RAG", position=1),+ ]+ )+ manifest, index = render_topic_manifest(materials)++ assert materials.warnings == ["notebook:nb_1"]+ # The healthy book still arrived.+ assert sorted(index) == ["bk-bk_1-ch_a", "bk-bk_1-ch_b"]+ assert "could not be loaded" in manifest+++def test_notebook_becomes_one_source_carrying_its_records(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ records = [+ {"id": "r1", "title": "Multi-hop failure", "output": "Linear RAG cannot chain."},+ {"id": "r2", "title": "Agent OS", "output": "Planning, memory, tools."},+ ]+ monkeypatch.setattr(+ "deeptutor.services.notebook.get_notebook_manager",+ lambda: SimpleNamespace(get_records_by_references=lambda refs: records),+ )+ materials = build_topic_materials([_source(TopicSourceKind.NOTEBOOK, "nb_1", "Study log")])+ manifest, index = render_topic_manifest(materials)++ assert list(index) == ["nb-topic-nb_1"]+ assert "Linear RAG cannot chain." in index["nb-topic-nb_1"]+ assert "Planning, memory, tools." in index["nb-topic-nb_1"]+ assert "Study log (2 records)" in manifestdiff --git a/deeptutor/learning/topic_materials.py b/deeptutor/learning/topic_materials.pynew file mode 100644index 000000000..0170b3eb5--- /dev/null+++ b/deeptutor/learning/topic_materials.py@@ -0,0 +1,371 @@+"""Expose a mastery topic's selected materials to the tutoring turn.++A topic's sources are chosen once, in the create-topic wizard, and were until+now consumed exactly once — to ground the outline generation. Nothing carried+them into tutoring, so the tutor taught a learner's own book from parametric+memory alone while its system prompt claimed to be teaching *from* it.++This module closes that gap by expressing topic materials in the vocabulary the+chat runtime already speaks: an *Attached Sources* manifest plus a+``{source_id: full_text}`` index. Filling those two values on a mastery turn is+enough to activate the whole existing machinery —+:class:`~deeptutor.capabilities.explore_context.ExploreContextCapability`+activates on a non-empty ``source_index`` and runs its ``read_source``+investigation before the tutor's first LLM call. No new tool, no new loop.++Granularity is per **chapter**, not per book: a whole book cannot be read into+one tool result, and a chapter is the unit a tutor actually needs for one+knowledge point. Notebooks stay whole — they are already record-sized.++Knowledge bases are listed but carry no ``source_id``: they are searched with+``rag``, not read. Listing them anyway is the point — the tutor must be able to+tell what it has from what it merely knows the name of.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import logging+from typing import Any, Iterable++logger = logging.getLogger(__name__)++# One chapter's serialized text. Matches the chat book-context page budget, so+# a chapter read here costs the tutor what a page selection costs chat.+MAX_CHAPTER_CHARS = 24_000+# Whole-book and whole-notebook ceilings. These bound the in-memory index only+# (the manifest itself lists identities, never full text), so they can be+# generous without touching the prompt budget.+MAX_BOOK_CHARS = 240_000+MAX_NOTEBOOK_CHARS = 120_000+MAX_TOTAL_CHARS = 600_000+# A book with hundreds of chapters would otherwise bury the manifest.+MAX_CHAPTERS_PER_BOOK = 40+# Per-row hint length. Long enough to choose a chapter, short enough that a+# 40-chapter book stays readable.+MAX_OUTLINE_CHARS = 220+++@dataclass(frozen=True)+class TopicMaterial:+ """One row of the topic-materials manifest.++ ``sid`` is empty for materials that are searched rather than read (a+ knowledge base), and for materials that could not be loaded. Only rows with+ a ``sid`` reach ``source_index``.+ """++ sid: str+ kind: str+ name: str+ outline: str = ""+ full_text: str = ""+ available: bool = True+ note: str = ""++ @property+ def readable(self) -> bool:+ return bool(self.sid and self.full_text.strip())+++@dataclass+class TopicMaterials:+ materials: list[TopicMaterial] = field(default_factory=list)+ warnings: list[str] = field(default_factory=list)++ def is_empty(self) -> bool:+ return not self.materials++ def source_index(self) -> dict[str, str]:+ return {m.sid: m.full_text for m in self.materials if m.readable}+++def _clip(text: str, limit: int) -> str:+ cleaned = (text or "").strip()+ if len(cleaned) <= limit:+ return cleaned+ return cleaned[:limit].rstrip() + "…"+++def _format_size(char_count: int) -> str:+ if char_count >= 1024:+ return f"~{round(char_count / 1024)} KB"+ return f"~{char_count} chars"+++def _load_book_materials(source_id: str, label: str, budget: int) -> list[TopicMaterial]:+ """One material per chapter, so the tutor can read the part it needs.++ A chapter with no generated pages yet is still listed — as unreadable, with+ the reason — because "this chapter exists but has not been written" is+ something the tutor must be able to say instead of inventing its contents.+ """+ from deeptutor.book.context import build_book_context+ from deeptutor.book.storage import get_book_storage++ storage = get_book_storage()+ book = storage.load_book(source_id)+ spine = storage.load_spine(source_id)+ if book is None or spine is None or not spine.chapters:+ return [+ TopicMaterial(+ sid="",+ kind="book",+ name=label,+ available=False,+ note="book has no generated chapters yet",+ )+ ]++ title = str(getattr(book, "title", "") or label).strip() or label+ materials: list[TopicMaterial] = []+ spent = 0+ chapters = sorted(spine.chapters, key=lambda chapter: chapter.order)+ for index, chapter in enumerate(chapters[:MAX_CHAPTERS_PER_BOOK], start=1):+ chapter_name = f"{title} · {index}. {_clean_name(chapter.title) or chapter.id}"+ outline = _clip(+ chapter.summary or "; ".join(chapter.learning_objectives),+ MAX_OUTLINE_CHARS,+ )+ if not chapter.page_ids:+ materials.append(+ TopicMaterial(+ sid="",+ kind="book",+ name=chapter_name,+ outline=outline,+ available=False,+ note="not written yet",+ )+ )+ continue+ if spent >= budget:+ materials.append(+ TopicMaterial(+ sid="",+ kind="book",+ name=chapter_name,+ outline=outline,+ available=False,+ note="beyond this turn's material budget",+ )+ )+ continue+ result = build_book_context(+ [{"book_id": source_id, "page_ids": list(chapter.page_ids)}],+ storage=storage,+ max_chars=min(MAX_CHAPTER_CHARS, budget - spent),+ )+ text = result.text.strip()+ if not text:+ materials.append(+ TopicMaterial(+ sid="",+ kind="book",+ name=chapter_name,+ outline=outline,+ available=False,+ note="no readable content",+ )+ )+ continue+ spent += len(text)+ materials.append(+ TopicMaterial(+ sid=f"bk-{source_id}-{chapter.id}",+ kind="book",+ name=chapter_name,+ outline=outline,+ full_text=text,+ )+ )+ if len(chapters) > MAX_CHAPTERS_PER_BOOK:+ materials.append(+ TopicMaterial(+ sid="",+ kind="book",+ name=f"{title} · +{len(chapters) - MAX_CHAPTERS_PER_BOOK} more chapters",+ available=False,+ note="not listed this turn",+ )+ )+ return materials+++def _load_notebook_material(source_id: str, label: str, budget: int) -> TopicMaterial:+ """A notebook stays one material: its records are already record-sized."""+ from deeptutor.services.notebook import get_notebook_manager++ records = get_notebook_manager().get_records_by_references(+ [{"notebook_id": source_id, "record_ids": []}]+ )+ if not records:+ return TopicMaterial(+ sid="",+ kind="notebook",+ name=label,+ available=False,+ note="notebook is empty or unreadable",+ )+ blocks: list[str] = []+ spent = 0+ limit = min(MAX_NOTEBOOK_CHARS, budget)+ for record in records:+ title = _clean_name(str(record.get("title") or record.get("name") or "")) or "Untitled"+ body = str(record.get("output") or record.get("summary") or "").strip()+ if not body:+ continue+ block = f"## {title}\n{body}"+ if spent + len(block) > limit:+ break+ blocks.append(block)+ spent += len(block)+ if not blocks:+ return TopicMaterial(+ sid="",+ kind="notebook",+ name=label,+ available=False,+ note="records have no readable content",+ )+ outline = _clip(+ "; ".join(+ _clean_name(str(record.get("title") or ""))+ for record in records[:8]+ if record.get("title")+ ),+ MAX_OUTLINE_CHARS,+ )+ return TopicMaterial(+ sid=f"nb-topic-{source_id}",+ kind="notebook",+ name=f"{label} ({len(blocks)} records)",+ outline=outline,+ full_text="\n\n".join(blocks),+ )+++def _clean_name(value: str) -> str:+ return " ".join(str(value or "").split())+++def build_topic_materials(sources: Iterable[Any]) -> TopicMaterials:+ """Resolve a topic's persisted sources into readable / searchable rows.++ Synchronous storage I/O — call it off the event loop. One unloadable source+ degrades to an ``unavailable`` row and never takes the turn down with it:+ tutoring that silently loses a material is worse than tutoring that says so.+ """+ result = TopicMaterials()+ budget = MAX_TOTAL_CHARS+ for source in sorted(sources, key=lambda item: getattr(item, "position", 0)):+ kind = getattr(getattr(source, "kind", None), "value", None) or str(+ getattr(source, "kind", "")+ )+ label = _clean_name(str(getattr(source, "label", "") or "")) or "Untitled"+ source_id = str(getattr(source, "source_id", "") or "").strip()+ available = bool(getattr(source, "available", True))+ # The goal is already the topic's stated objective; repeating it as a+ # readable material would only invite the tutor to "read" it.+ if kind == "goal":+ continue+ if not available or not source_id:+ result.materials.append(+ TopicMaterial(+ sid="",+ kind=kind or "unknown",+ name=label,+ available=False,+ note="marked unavailable when the topic was created",+ )+ )+ continue+ if kind == "knowledge_base":+ result.materials.append(+ TopicMaterial(+ sid="", kind=kind, name=label, note=f"search with rag: kb_name={source_id!r}"+ )+ )+ continue+ try:+ if kind == "book":+ loaded = _load_book_materials(source_id, label, budget)+ elif kind == "notebook":+ loaded = [_load_notebook_material(source_id, label, budget)]+ else:+ loaded = [+ TopicMaterial(+ sid="",+ kind=kind or "unknown",+ name=label,+ available=False,+ note="this material type cannot be read during tutoring",+ )+ ]+ except Exception:+ logger.exception("Failed to load topic material kind=%s id=%s", kind, source_id)+ result.warnings.append(f"{kind}:{source_id}")+ loaded = [+ TopicMaterial(+ sid="",+ kind=kind or "unknown",+ name=label,+ available=False,+ note="could not be loaded",+ )+ ]+ for material in loaded:+ budget -= len(material.full_text)+ result.materials.append(material)+ return result+++def render_topic_manifest(materials: TopicMaterials) -> tuple[str, dict[str, str]]:+ """Render the manifest block and the ``read_source`` index.++ The closing rule is the whole point of the block: an unreadable material+ must be *named* as unreadable, so the tutor answers "I can see the outline+ but not the text" instead of asserting it has read a book it never saw.+ """+ if materials.is_empty():+ return "", {}++ rows: list[str] = []+ for material in materials.materials:+ if material.readable:+ row = (+ f"- id={material.sid} type={material.kind} name={material.name!r}"+ f" size={_format_size(len(material.full_text))}"+ )+ elif material.available and material.note:+ row = f"- type={material.kind} name={material.name!r} {material.note}"+ else:+ row = (+ f"- type={material.kind} name={material.name!r}"+ f" unavailable: {material.note or 'unknown reason'}"+ )+ if material.outline:+ row += f"\n about: {material.outline!r}"+ rows.append(row)++ header = (+ "[Topic Materials]\n"+ "The materials the learner chose for this mastery topic. They are the "+ "ground truth for this topic — teach from them, not from memory.\n"+ "- Rows with an `id` hold real text: call read_source(id) for the one a "+ "knowledge point actually needs. Do not read them all up front.\n"+ "- Rows marked `search with rag` are knowledge bases: query them with the "+ "rag tool using the kb_name shown.\n"+ "- Rows marked `unavailable` cannot be read at all. Never describe or "+ "quote their contents. Say plainly that the material is not readable and "+ "offer to teach from what is available."+ )+ return header + "\n\n" + "\n\n".join(rows), materials.source_index()+++__all__ = [+ "TopicMaterial",+ "TopicMaterials",+ "build_topic_materials",+ "render_topic_manifest",+]diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex ebb4cbb1c..016fda38e 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -253,6 +253,41 @@ def _mastery_path_id(value: Any) -> str:return str(value or "").strip()+def _topic_material_manifest(path_id: str) -> tuple[str, dict[str, str]]:+ """Load a mastery topic's materials as (manifest, read_source index).++ Storage-bound and synchronous; the caller runs it off the event loop. A+ topic that cannot be loaded yields no manifest rather than failing the turn+ — losing the materials degrades the lesson, losing the turn ends it.+ """+ try:+ from deeptutor.learning.storage import LearningStore+ from deeptutor.learning.topic_materials import (+ build_topic_materials,+ render_topic_manifest,+ )++ store = LearningStore()+ progress = store.load(path_id)+ if progress is None:+ return "", {}+ topic = store.get_topic(path_id, progress=progress)+ if topic is None or not topic.sources:+ return "", {}+ materials = build_topic_materials(topic.sources)+ if materials.warnings:+ logger.warning(+ "Mastery topic %s: %d material(s) could not be loaded: %s",+ path_id,+ len(materials.warnings),+ ", ".join(materials.warnings),+ )+ return render_topic_manifest(materials)+ except Exception:+ logger.exception("Failed to build topic materials for mastery path %s", path_id)+ return "", {}++# Reading material ids are content hashes; anything else is a client bug or an# injection attempt, so the shape is enforced here rather than deeper in._READING_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")@@ -2366,6 +2401,24 @@ class TurnRuntimeManager:context_parts.append(f"[User Question]\n{raw_user_content}")effective_user_message = "\n\n".join(context_parts)+ # A mastery topic carries materials the learner chose once, in the+ # create-topic wizard. They grounded the outline and were then never+ # seen again: the tutor taught the learner's own book from parametric+ # memory while its prompt claimed to teach *from* it. Expressing them+ # the way chat expresses attachments — manifest + read_source index —+ # is enough to hand them to the tutor, because the explore_context+ # pre-pass activates on a non-empty ``source_index`` and investigates+ # them before the tutor's first LLM call.+ #+ # Guarded on an empty index so materials the learner attached to+ # *this turn* (which took the chat path above) always win.+ if capability_name == "mastery_path" and not source_index:+ topic_path_id = _mastery_path_id(payload.get("mastery_path_id"))+ if topic_path_id:+ source_manifest_text, source_index = await asyncio.to_thread(+ _topic_material_manifest, topic_path_id+ )+conversation_history = list(history_result.conversation_history)conversation_context_text = history_result.context_text