Skip to content

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

perf(mastery): seed fresh status before the first model call (#1713)

ZyPulse5ff2b93cf6ac
diff --git a/README.md b/README.md
index 449d46fcd..aebc69fbc 100644
--- a/README.md
+++ b/README.md
@@ -1161,6 +1161,15 @@ Licensed under the [Apache License 2.0](LICENSE).
</div>
+### Mastery turn grounding
+
+Mastery turns read the active path's status before the first model request, using
+the same status tool and mastery gates as an explicit tool call. This snapshot is
+fresh for each turn, includes the active session mode, and is never cached across
+turns. A failed read falls back to `mastery_status`; after changing the path, mode,
+outline, or progress, the tutor can refresh through that tool. Card grading and
+its existing handoff remain unchanged.
+
### Repeated image attachments
The agent loop sends identical inline user images once per request and replaces later
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index ef8047baa..65f45a7e6 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -15,6 +15,7 @@ it is only ever a clarifying question.
from __future__ import annotations
from collections.abc import Callable
+import json
import logging
import re
from typing import Any
@@ -406,6 +407,48 @@ class MasteryLoopCapability:
state["card_posted"] = False
return ""
+ async def pre_loop(
+ self, context: UnifiedContext, stream: Any, *, usage: Any = None
+ ) -> PromptBlock | None:
+ """Read current state once before the first model call, without an LLM.
+
+ This is a fresh read for this turn, never a session cache. Reuse the
+ status tool so objective gates and pending answers have one authority.
+ The loop's pre-pass wrapper falls back to the tool on read failure.
+ """
+ if not self.is_active(context) or not context.metadata.get("mastery_path_id"):
+ return None
+ from deeptutor.capabilities.mastery.tools import MasteryStatusTool
+
+ binding = (
+ context.metadata.get("mastery_path_id"),
+ context.metadata.get("mastery_session_mode"),
+ )
+ result = await MasteryStatusTool().execute(
+ **self.augment_kwargs("mastery_status", {}, context)
+ )
+ if not result.success:
+ return None
+ # A rebind during the read must not seed the new path with old state.
+ current = (
+ context.metadata.get("mastery_path_id"),
+ context.metadata.get("mastery_session_mode"),
+ )
+ if (
+ binding != current
+ or json.loads(result.content).get("path_id") != str(binding[0]).strip()
+ ):
+ return None
+ return PromptBlock(
+ "mastery_status_snapshot",
+ "[Current-turn mastery_status snapshot]\n"
+ "The runtime has already read mastery_status for this turn and active path. "
+ "Use this result directly; do not call mastery_status again just to begin. "
+ "Refresh with mastery_status after changing the path, mode, outline, or progress "
+ "when updated state is needed. Earlier turns' snapshots are historical only.\n"
+ + result.content,
+ )
+
def pre_loop_seed(self, context: UnifiedContext) -> str:
"""Hand over whatever this turn already settled on the open card.
diff --git a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml
index eacee3629..bc3fa186e 100644
--- a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml
+++ b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml
@@ -30,7 +30,7 @@ loop:
system: |-
You advance this tutoring session in a loop. Each round you may call tools: read the outline, search the materials, pose a question, grade one, record a result.
- **Call `mastery_status` first, every round.** It returns the objective to work on now, any question awaiting an answer, due reviews, and the whole outline. Trust it to choose the objective — never guess what comes next.
+ **Begin each turn with current `mastery_status` state.** Use the current-turn runtime snapshot when provided; otherwise call `mastery_status` first. Snapshots from earlier turns are historical. Refresh after changing the path, mode, outline, or progress when updated state is needed. It returns the objective to work on now, any question awaiting an answer, due reviews, and the whole outline. Trust it to choose the objective — never guess what comes next.
A round ends in one of two ways, and both are normal:
diff --git a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml
index 23c8980d4..b82895658 100644
--- a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml
+++ b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml
@@ -29,7 +29,7 @@ loop:
system: |-
你在一个循环里推进这次辅导。每一轮你都可以调用工具:读大纲、检索教材、出题、批改、记录。
- **每一轮先调用 `mastery_status`。** 它会返回当前要攻克的知识点、是否有待批改的作答、到期复习项,以及整份大纲。请信任它来决定学什么——绝不要自己猜下一个知识点。
+ **每一轮先读取当前 `mastery_status` 状态。** 如果运行时已提供本轮快照,直接使用;否则先调用 `mastery_status`。以前轮次的快照只作历史记录。切换路径、模式或修改大纲、进度后,需要新状态时重新调用。 它会返回当前要攻克的知识点、是否有待批改的作答、到期复习项,以及整份大纲。请信任它来决定学什么——绝不要自己猜下一个知识点。
一轮有两种结束方式,两种都正常:
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 97c01f578..26106d631 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -698,7 +698,7 @@ async def _unbuilt_status_message(
class MasteryStatusTool(BaseTool):
- """Read the current objective + map snapshot. Call FIRST every turn."""
+ """Read current state, or refresh a current-turn runtime snapshot."""
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
@@ -707,8 +707,10 @@ class MasteryStatusTool(BaseTool):
"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."
+ "(new / learning / mastered). Use the current-turn runtime snapshot "
+ "when supplied; otherwise call this FIRST. Refresh after changing "
+ "the path, mode, outline, or progress when updated state is needed. "
+ "Never guess the next objective or reuse an earlier turn's snapshot."
),
parameters=[],
)
diff --git a/tests/capabilities/test_mastery_status_snapshot.py b/tests/capabilities/test_mastery_status_snapshot.py
new file mode 100644
index 000000000..94f12002d
--- /dev/null
+++ b/tests/capabilities/test_mastery_status_snapshot.py
@@ -0,0 +1,91 @@
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.capabilities.mastery.loop import MasteryLoopCapability
+from deeptutor.capabilities.mastery.tools import MasteryStatusTool
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.tool_protocol import ToolResult
+
+
+async def test_snapshot_is_fresh_scoped_and_includes_pending_answer(monkeypatch):
+ calls = []
+
+ async def read(**kwargs):
+ calls.append(kwargs)
+ return ToolResult(
+ success=True,
+ content=json.dumps(
+ {
+ "path_id": kwargs["_mastery_path_id"],
+ "revision": len(calls),
+ "pending_interaction": {"status": "answered", "learner_answer": "B"},
+ }
+ ),
+ )
+
+ monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
+ cap = MasteryLoopCapability()
+ context = UnifiedContext(
+ session_id="s",
+ metadata={
+ "mastery_mode": True,
+ "mastery_path_id": "p1",
+ "mastery_session_mode": "review",
+ },
+ )
+ first = await cap.pre_loop(context, None)
+ assert '"learner_answer": "B"' in first.content
+ assert calls[0]["_mastery_session_mode"] == "review"
+ context.metadata["mastery_path_id"] = "p2"
+ second = await cap.pre_loop(context, None)
+ assert '"path_id": "p2"' in second.content
+ assert '"revision": 2' in second.content
+ assert "p1" not in second.content
+
+
+async def test_no_snapshot_on_read_failure_or_inactive_path(monkeypatch):
+ read = AsyncMock(return_value=ToolResult(success=False, content="unavailable"))
+ monkeypatch.setattr(MasteryStatusTool, "execute", read)
+ cap = MasteryLoopCapability()
+ assert await cap.pre_loop(UnifiedContext(), None) is None
+ read.assert_not_called()
+ context = UnifiedContext(metadata={"mastery_mode": True, "mastery_path_id": "p"})
+ assert await cap.pre_loop(context, None) is None
+ assert "otherwise call this FIRST" in MasteryStatusTool().get_definition().description
+
+
+async def test_binding_change_during_read_discards_snapshot(monkeypatch):
+ context = UnifiedContext(metadata={"mastery_mode": True, "mastery_path_id": "p1"})
+
+ async def read(**kwargs):
+ context.metadata["mastery_path_id"] = "p2"
+ return ToolResult(success=True, content=json.dumps({"path_id": "p1"}))
+
+ monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
+ assert await MasteryLoopCapability().pre_loop(context, None) is None
+
+
+async def test_prepass_failure_keeps_tool_fallback_and_grade_seed(monkeypatch):
+ from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+
+ async def read(**kwargs):
+ raise RuntimeError("unavailable")
+
+ monkeypatch.setattr(MasteryStatusTool, "execute", staticmethod(read))
+ context = UnifiedContext(
+ metadata={
+ "mastery_mode": True,
+ "mastery_path_id": "p1",
+ "mastery_card_grade": {"is_correct": True, "result": {"learner_answer": "B"}},
+ }
+ )
+ pipeline = AgenticChatPipeline(language="en")
+ assert await pipeline._capability_pre_loop_briefings(context, None) == ""
+ assert "already graded it: correct" in pipeline._capability_pre_loop_seed(context)
+ assert "otherwise call this FIRST" in MasteryStatusTool().get_definition().description