Skip to content

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

fix: reject unposted mastery card delivery claims

Wubian1114b8e9bacbbc3
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index dc3f3ff73..4fbd54281 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -74,6 +74,48 @@ _PROMISE_TAIL_CHARS = 160
# more reliable than recognising the wording, which varies every turn.
_DANGLING_LEAD_IN_CHARS = frozenset("::")
+# Delivery claims can precede a long explanation, unlike the vague question
+# announcements above. Check clauses across the reply, but require both a
+# concrete card/question and a delivery verb rather than the word "card" alone.
+_CARD_DELIVERY_RE = re.compile(
+ r"(?:卡片|题卡|(?:这|那|一|下一)道题|题目)[^。!?\n,,;;]{0,24}"
+ r"(?:重开|开出来|(?:放|挂|贴|发)(?:上来|上去|出来|上了|好了)|"
+ r"(?:生成|展示)(?:了|好|出来)|(?:就)?在(?:下面|下方))|"
+ r"先探一题|"
+ r"\bI(?:['’]ve| have)? (?:just |now )?(?:posted|reopened|displayed) "
+ r"(?:the|a|this) (?:(?:question|quiz|answer) )?card\b|"
+ r"\b(?:the|this) (?:(?:question|quiz|answer) )?card "
+ r"(?:is|has been) (?:ready|posted|displayed|reopened|below)\b",
+ re.IGNORECASE,
+)
+_NON_DELIVERY_CLAUSE_RE = re.compile(
+ r"没有|没能|未能|尚未|还没|不会|不再|不要|不能|并未|无法|失败|"
+ r"上次|上一轮|刚才|之前|如果|假如|是否|你说|[吗??]|^\s*等|"
+ r"\b(?:not|never|if|earlier|previously|yesterday)\b",
+ re.IGNORECASE,
+)
+_QUOTED_CARD_TEXT_RE = re.compile(
+ r"```.*?```|~~~.*?~~~|`[^`\n]*`|“[^”]*”|「[^」]*」|\"[^\"\n]*\"|^\s*>[^\n]*",
+ re.DOTALL | re.MULTILINE,
+)
+_CONDITIONAL_DELIVERY_RE = re.compile(
+ r"^\s*(?:等|如果|假如|(?:学|讲|看)完.{0,12}(?:以后|之后)|稍后|下一轮|"
+ r"if\b|when\b|after\b)",
+ re.IGNORECASE,
+)
+
+
+def _claims_card_delivery(text: str) -> bool:
+ """Recognise current delivery claims without treating quoted reports as actions."""
+ prose = _QUOTED_CARD_TEXT_RE.sub(" ", text)
+ for sentence in re.split(r"[。!\n]|(?<=[.!?])\s+", prose):
+ if _CONDITIONAL_DELIVERY_RE.search(sentence):
+ continue
+ for clause in re.split(r"[,,;;]", sentence):
+ if _CARD_DELIVERY_RE.search(clause) and not _NON_DELIVERY_CLAUSE_RE.search(clause):
+ return True
+ return False
+
def _looks_like_plain_choice_quiz(text: str) -> bool:
"""Recognise a rendered A-D option list with high precision.
@@ -272,7 +314,11 @@ class MasteryLoopCapability:
if not self.is_active(context):
return None
state = context.extension("mastery")
- if _announces_an_unposed_question(final_text):
+ if not state.get("card_posted") and (
+ _announces_an_unposed_question(final_text) or _claims_card_delivery(final_text)
+ ):
+ # Argument binding sets quiz_awaiting_grade even when registration
+ # fails. Only the tool's success callback marks a card as posted.
# "Let us see what you already know:" and then nothing. The learner
# is left reading a promise with no card under it, and the turn is
# over — this reply announced the question instead of posing it.
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index ebe562b63..2662c81e2 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -14,11 +15,14 @@ from deeptutor.agents.loop.agent_loop import InlineThinkFilter
from deeptutor.capabilities.explore_context import explorer as explorer_mod
from deeptutor.capabilities.mastery import MASTERY_TOOL_NAMES
from deeptutor.capabilities.mastery.pipeline import MasteryLoopPipeline
+from deeptutor.capabilities.mastery.tools import MasteryQuizTool
from deeptutor.capabilities.partner_group.tools import InvokeOtherTool
from deeptutor.core.context import Attachment, TurnRuntimeContext, UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.tool_protocol import ToolResult
from deeptutor.core.trace import ANSWER_BEARING_CALL_KINDS
+from deeptutor.learning.models import KnowledgePoint, LearningModule, LearningProgress
+from deeptutor.learning.storage import LearningStore
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.llm import LLMProviderTransportError, LLMReasoningBudgetExhausted
from deeptutor.services.llm.provider_core.openai_responses import convert_messages
@@ -1319,6 +1323,125 @@ async def test_repeated_plain_choice_failure_is_never_published_as_a_finish(
assert result.metadata["response"] == ""
[email protected]("repair", ["new", "existing", "tool_failure", "repeat"])
+async def test_mastery_card_promise_repair_uses_real_question_tool(
+ repair: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A text-only claim repairs to a durable card or a bounded failed turn."""
+ monkeypatch.setenv("DEEPTUTOR_WORKSPACE_ROOT", str(tmp_path))
+
+ def init_store(self: LearningStore, root: Path | None = None) -> None:
+ self._root = tmp_path / "learning"
+ self._root.mkdir(parents=True, exist_ok=True)
+
+ monkeypatch.setattr(LearningStore, "__init__", init_store)
+ LearningStore().save(
+ LearningProgress(
+ book_id="p1",
+ modules=[
+ LearningModule(
+ id="m1",
+ name="Sorting",
+ order=0,
+ knowledge_points=[
+ KnowledgePoint(
+ id="kp1", name="Bubble sort", type="procedure", module_id="m1"
+ )
+ ],
+ )
+ ],
+ )
+ )
+ quiz_args = {
+ "knowledge_point_id": "kp1",
+ "question": "After one left-to-right ascending bubble-sort pass on [3, 1, 2]?",
+ "expected_answer": "A",
+ "options": [{"label": "A", "body": "1, 2, 3"}, {"label": "B", "body": "1, 3, 2"}],
+ "explanation": "The largest value 3 moves to the end in this pass.",
+ }
+ old_id = None
+ if repair == "existing":
+ old = await MasteryQuizTool().execute(
+ **quiz_args, _mastery_path_id="p1", _session_id="s1", _turn_id="previous"
+ )
+ assert old.success
+ old_id = old.metadata["mastery_question"]["question_id"]
+
+ class RealQuizRegistry(_Registry):
+ def build_openai_schemas(self, _enabled: list[str]) -> list[dict[str, Any]]:
+ return [MasteryQuizTool().get_definition().to_openai_schema()]
+
+ async def execute(self, name: str, **kwargs: Any) -> ToolResult:
+ self.executed.append({"name": name, "kwargs": kwargs})
+ assert name == "mastery_quiz"
+ return await MasteryQuizTool().execute(**kwargs)
+
+ promise = "卡片这次重开一遍,题面我直接写在题干里了。"
+ script = [[_llm_chunk(content=promise, finish_reason="stop")]]
+ if repair == "repeat":
+ script.append([_llm_chunk(content=promise, finish_reason="stop")])
+ else:
+ script.append(
+ [
+ _llm_chunk(
+ tool_calls=[
+ {
+ "id": "quiz-1",
+ "name": "mastery_quiz",
+ "arguments": json.dumps({} if repair == "tool_failure" else quiz_args),
+ }
+ ],
+ finish_reason="tool_calls",
+ )
+ ]
+ )
+ if repair == "tool_failure":
+ script.append([_llm_chunk(content=promise, finish_reason="stop")])
+ client = _ScriptedChatClient(script)
+ registry = RealQuizRegistry()
+ pipeline = MasteryLoopPipeline(language="zh")
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["mastery_quiz"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="没有卡片",
+ enabled_tools=["mastery_quiz"],
+ metadata={
+ "mastery_mode": True,
+ "mastery_path_id": "p1",
+ "mastery_session_mode": "study",
+ "turn_id": "repair-turn",
+ },
+ )
+ events = await _run(pipeline, context)
+ cards = [
+ e.metadata["tool_metadata"]["mastery_question"]
+ for e in events
+ if e.type == StreamEventType.TOOL_RESULT
+ and "mastery_question" in e.metadata.get("tool_metadata", {})
+ ]
+ assert promise not in _answer_text(events)
+ assert "mastery_quiz" in client.calls[1]["messages"][-1]["content"]
+ assert any(s["function"]["name"] == "mastery_quiz" for s in client.calls[1]["tools"])
+ assert client.call_count == (3 if repair == "tool_failure" else 2)
+ succeeded = repair in {"new", "existing"}
+ assert _result(events).metadata["completed"] is succeeded
+ if succeeded:
+ assert len(cards) == 1
+ persisted = LearningStore().load("p1").pending_question
+ assert persisted is not None
+ assert cards[0]["question_id"] == persisted.question_id
+ assert cards[0]["prompt"] == quiz_args["question"]
+ if old_id:
+ assert cards[0]["question_id"] == old_id
+ else:
+ assert cards == []
+ assert LearningStore().load("p1").pending_question is None
+ assert _result(events).metadata["response"] == ""
+
+
@pytest.mark.asyncio
async def test_truncated_pure_reasoning_round_is_told_to_act_not_continue(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.py
index 1d2a01516..c666d31ad 100644
--- a/tests/capabilities/test_mastery_capability.py
+++ b/tests/capabilities/test_mastery_capability.py
@@ -137,6 +137,77 @@ def test_announced_but_unposed_question_is_redirected():
assert "SAME round" in instruction
+ "reply",
+ [
+ "按老规矩先探一题:凭印象选就行——这题考的是它俩的区别。",
+ "那就先把探底那道题放上来——凭印象选就好。",
+ "这次的卡片我直接开出来——就是探底那道。",
+ "卡片这次重开一遍,题面我直接写在题干里了。",
+ "好,这次的卡片我直接重开一遍,一步一步来。",
+ "卡片这次真挂上了。" + "冒泡排序比较相邻两个元素。" * 25,
+ "卡片就在下面,选一个字母就行。",
+ "卡片已经生成了,直接作答就行。",
+ "这次把卡片放好了,请选择答案。",
+ "上次卡片没有生成,这次我把卡片重新发出来。",
+ "I've posted the question card below. Choose an option.",
+ "The quiz card is ready below. Choose an option.",
+ "I have reopened the card. Choose an option.",
+ ],
+)
+def test_card_delivery_claim_needs_a_posted_card(reply: str) -> None:
+ """Real lead-ins without any question must enter the existing repair path."""
+ context = _context()
+ # A previous grade must not exempt a promise to pose the next question.
+ context.metadata["mastery_card_grade"] = {"is_correct": True}
+ instruction = MasteryLoopCapability().finish_instruction(context, reply)
+ assert instruction is not None
+ assert "mastery_quiz" in instruction
+
+
+ "reply",
+ [
+ "上次卡片没有生成,这次先讲冒泡排序。",
+ "卡片没有放上来,我先说明原因。",
+ "这次不会把卡片放上来,先讲概念。",
+ "如果卡片放上来了,就可以作答。",
+ "等讲完知识点,再把卡片放上来。",
+ "学完以后,我会把卡片放上来。",
+ "卡片暂时无法放上来,我先说明原因。",
+ "卡片放上来失败了,请稍后重试。",
+ "上一轮我把卡片放上来了,这次解释答案。",
+ "你说卡片放上来了,但我没有看到。",
+ "你看到卡片放上来了吗?",
+ "“卡片就在下面”这句话不能证明出题成功。",
+ "> 卡片就在下面\n\n这是之前回复的引用。",
+ "```text\n卡片就在下面\n```\n\n这是日志示例。",
+ "I have not posted the question card yet.",
+ "If the quiz card is ready below, answer it.",
+ "Earlier I posted the question card. Now let us review your answer.",
+ "冒泡排序通过交换相邻元素完成排序。",
+ ],
+)
+def test_card_discussion_is_not_a_delivery_claim(reply: str) -> None:
+ """Negation, quotation, history and teaching must still finish normally."""
+ assert MasteryLoopCapability().finish_instruction(_context(), reply) is None
+
+
+def test_card_delivery_claim_uses_success_not_argument_binding() -> None:
+ """Binding a quiz is not success; only the tool's success callback is."""
+ context = _context()
+ capability = MasteryLoopCapability()
+ kwargs = capability.augment_kwargs("mastery_quiz", {}, context)
+ reply = "卡片这次重开一遍。"
+ assert capability.finish_instruction(context, reply) is not None
+ kwargs["_end_turn_on_card"]()
+ assert capability.finish_instruction(context, reply) is None
+
+
+def test_card_delivery_claim_does_not_guard_plain_chat() -> None:
+ assert MasteryLoopCapability().finish_instruction(UnifiedContext(), "卡片就在下面。") is None
+
+
def test_runtime_grading_also_frees_the_review_to_finish():
"""A ruling the runtime made counts as this turn having graded.