DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): don't freeze choice gates on clarifying composer text
ZQR110185602ca16178
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex 2380ebb36..41c243e48 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -200,19 +200,41 @@ class MasteryLoopCapability:reply_text: str,answers: list[dict[str, str]] | None,) -> None:- """Commit the learner answer before giving it back to the LLM."""+ """Commit the learner answer before giving it back to the LLM.++ Clarifying composer text on a *choice* card (no option picked) must not+ be persisted as the formal answer — that freezes the gate when+ ``mastery_grade`` later refuses to map the prose onto an option (#1004).+ Leave the interaction awaiting so a later real pick can still commit.+ """path_id = str(context.metadata.get("mastery_path_id") or "").strip()if not path_id:return+ from deeptutor.learning.pending import is_readable_choice_answerfrom deeptutor.learning.service import LearningService- await asyncio.to_thread(- LearningService().record_question_answer,- path_id,- _answer_from_reply(ask_user, reply_text=reply_text, answers=answers),- session_id=str(context.session_id or ""),- turn_id=str(context.metadata.get("turn_id") or ""),- )+ answer = _answer_from_reply(ask_user, reply_text=reply_text, answers=answers)+ from_card = _reply_matches_card(ask_user, answers)++ def _commit() -> None:+ service = LearningService()+ if not from_card:+ interaction = service.store.get_active_interaction(path_id)+ question = interaction.question if interaction is not None else None+ if (+ question is not None+ and question.question_type == "choice"+ and not is_readable_choice_answer(answer, question.options)+ ):+ return+ service.record_question_answer(+ path_id,+ answer,+ session_id=str(context.session_id or ""),+ turn_id=str(context.metadata.get("turn_id") or ""),+ )++ await asyncio.to_thread(_commit)def _path_binder(context: UnifiedContext) -> Callable[[str], None]:@@ -224,6 +246,17 @@ def _path_binder(context: UnifiedContext) -> Callable[[str], None]:return bind+def _reply_matches_card(+ ask_user: dict[str, Any],+ answers: list[dict[str, str]] | None,+) -> bool:+ """Whether the resume carried a structured answer for this ask_user card."""+ card_question_id = _first_question_id(ask_user)+ if not card_question_id:+ return False+ return any(entry.get("questionId") == card_question_id for entry in answers or [])++def _answer_from_reply(ask_user: dict[str, Any],*,diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex ca715a25a..2e816e673 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -636,8 +636,17 @@ class MasteryGradeTool(BaseTool):)if interaction is not None and interaction.status == InteractionStatus.ANSWERED:# The pause/resume boundary already committed the learner's exact- # reply. Never let a later model round paraphrase the graded input.- answer = interaction.user_answer+ # reply — unless that commit was unreadable clarifying prose on a+ # choice card (#1004), in which case a later readable answer may+ # still recover the gate.+ from deeptutor.learning.pending import is_readable_choice_answer++ stored = str(interaction.user_answer or "")+ question = interaction.question+ if question.question_type != "choice" or is_readable_choice_answer(+ stored, question.options+ ):+ answer = storedprogress_before = _load_path(service, path_id)if progress_before is None:return _no_built_path_result("mastery_grade")diff --git a/deeptutor/learning/pending.py b/deeptutor/learning/pending.pyindex 12c5d54b9..68f0583fb 100644--- a/deeptutor/learning/pending.py+++ b/deeptutor/learning/pending.py@@ -169,6 +169,18 @@ def resolve_choice_submission(answer: str, options: dict[str, str]) -> str:return mentioned[0] if len(mentioned) == 1 else ""+def is_readable_choice_answer(answer: str, options: list[str] | dict[str, str]) -> bool:+ """Whether *answer* identifies exactly one option on a choice question.++ Composer text that is a clarifying question (or otherwise unmappable) must+ not be treated as a committed pick — see mastery gate stall #1004.+ """+ option_map = parse_options(options) if isinstance(options, list) else options+ if not option_map:+ return False+ return bool(resolve_choice_submission(answer, option_map))++@dataclass(frozen=True, slots=True)class PublicPendingOption:"""One learner-visible option; ``id`` and ``label`` are intentionally stable."""@@ -237,6 +249,7 @@ __all__ = ["PublicPendingQuestion","format_options","has_option_bodies",+ "is_readable_choice_answer","option_label_intent","parse_options","positional_label",diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.pyindex 8e2c0ae00..09bfb43c8 100644--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@ -468,6 +468,30 @@ class LearningService:session_id=interaction.session_id,turn_id=interaction.turn_id,)+ elif (+ interaction.status == InteractionStatus.ANSWERED+ and interaction.question.question_type == "choice"+ ):+ # Recover from a prior unreadable composer commit (#1004): allow+ # a later readable pick to replace the stalled user_answer.+ from deeptutor.learning.pending import is_readable_choice_answer++ stored = str(interaction.user_answer or "")+ incoming = str(answer or "")+ if (+ not is_readable_choice_answer(stored, interaction.question.options)+ and is_readable_choice_answer(incoming, interaction.question.options)+ ):+ interaction.user_answer = incoming+ interaction.session_id = session_id or interaction.session_id+ interaction.turn_id = turn_id or interaction.turn_id+ tx.put_interaction(interaction)+ tx.emit(+ "interaction.answered",+ {"interaction_id": interaction.interaction_id},+ session_id=interaction.session_id,+ turn_id=interaction.turn_id,+ )return interaction_, interaction = self._store.mutate(book_id, record)@@ -517,20 +541,26 @@ class LearningService:raise NoPendingInteractionError("The question was abandoned")pending = interaction.question- raw_answer = (- interaction.user_answer- if interaction.status == InteractionStatus.ANSWERED- else str(answer or "")- )+ raw_answer = str(answer or "")if interaction.status == InteractionStatus.ANSWERED:+ stored = str(interaction.user_answer or "")if pending.question_type == "choice":from deeptutor.learning.pending import (has_option_bodies,+ is_readable_choice_answer,parse_options,resolve_choice_submission,)option_map = parse_options(pending.options)+ if is_readable_choice_answer(stored, option_map):+ raw_answer = stored+ elif is_readable_choice_answer(raw_answer, option_map):+ # Prior commit was unreadable clarifying text (#1004) —+ # accept the fresh readable answer and rewrite storage.+ interaction.user_answer = raw_answer+ else:+ raw_answer = storedif has_option_bodies(option_map):graded_answer = (resolve_choice_submission(raw_answer, option_map) or raw_answer@@ -542,6 +572,7 @@ class LearningService:raw_answer if answer_for_grading is None else answer_for_grading)else:+ raw_answer = storedgraded_answer = raw_answerelse:graded_answer = raw_answer if answer_for_grading is None else answer_for_gradingdiff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.pyindex 9ed07e27d..dd7e877e9 100644--- a/deeptutor/learning/tests/test_mastery_tools.py+++ b/deeptutor/learning/tests/test_mastery_tools.py@@ -831,6 +831,59 @@ async def test_status_recovers_answered_interaction_without_exposing_answer_key(assert graded["is_correct"] is True+async def test_grade_recovers_unreadable_choice_answer(path_id):+ """An unreadable clarifying commit must not permanently block grading (#1004)."""+ await _build_basic(path_id)+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = initial["next"]["knowledge_point_id"]+ quiz = json.loads(+ (+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Compute (2e^{iπ/3})³",+ expected_answer="A",+ options=["A: -8", "B: -6", "C: 8", "D: -2"],+ )+ ).content+ )+ from deeptutor.learning.service import LearningService++ # Simulate the pre-fix deadlock: clarifying prose already persisted.+ LearningService().record_question_answer(+ path_id,+ "先告诉我三角恒等式是什么?",+ interaction_id=quiz["question_id"],+ )+ stuck = LearningStore().get_interaction(path_id, quiz["question_id"])+ assert stuck is not None+ assert stuck.status == InteractionStatus.ANSWERED++ blocked = await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ question_id=quiz["question_id"],+ answer="先告诉我三角恒等式是什么?",+ )+ assert blocked.success is False+ assert "NOT graded" in blocked.content++ recovered = json.loads(+ (+ await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ question_id=quiz["question_id"],+ answer="A",+ )+ ).content+ )+ assert recovered["is_correct"] is True+ graded = LearningStore().get_interaction(path_id, quiz["question_id"])+ assert graded is not None+ assert graded.status == InteractionStatus.GRADED+ assert graded.user_answer == "A"++# ── assess: the qualitative gate ─────────────────────────────────────────────diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.pyindex 022f2a08d..e01e08bfa 100644--- a/tests/capabilities/test_mastery_capability.py+++ b/tests/capabilities/test_mastery_capability.py@@ -162,6 +162,80 @@ async def test_pause_and_resume_hooks_persist_interaction_boundaries(tmp_path, massert answered.user_answer == "B"+async def test_choice_clarifying_composer_text_does_not_commit_answer(tmp_path, monkeypatch):+ """Composer clarifying prose must not freeze a choice question as answered.++ Regression for #1004: typing "what is this?" into the composer used to+ persist as user_answer, after which mastery_grade could never map it to an+ option and the gate stalled forever.+ """+ _use_store_root(monkeypatch, tmp_path)+ pending = PendingQuestion(+ question_id="stable-question",+ knowledge_point_id="kp-1",+ prompt="Compute (2e^{iπ/3})³",+ question_type="choice",+ expected_answer="A",+ options=["A: -8", "B: -6", "C: 8", "D: -2"],+ )+ LearningStore().save(_progress_with_objective())+ LearningService().register_question(+ "path-1",+ pending,+ session_id="session-1",+ turn_id="turn-2",+ )+ ask_user = {"questions": [{"id": "stable-question", "prompt": pending.prompt}]}+ capability = MasteryLoopCapability()++ await capability.on_user_pause(_context(), ask_user)+ await capability.on_user_resume(+ _context(),+ ask_user,+ reply_text="先告诉我三角恒等式是什么?",+ answers=None,+ )++ still_open = LearningStore().get_interaction("path-1", "stable-question")+ assert still_open is not None+ assert still_open.status == InteractionStatus.AWAITING_INPUT+ assert still_open.user_answer == ""+++async def test_choice_composer_option_label_still_commits(tmp_path, monkeypatch):+ """Typing a readable option into the composer remains a valid commit."""+ _use_store_root(monkeypatch, tmp_path)+ pending = PendingQuestion(+ question_id="stable-question",+ knowledge_point_id="kp-1",+ prompt="Which colour?",+ question_type="choice",+ expected_answer="B",+ options=["A: red", "B: blue"],+ )+ LearningStore().save(_progress_with_objective())+ LearningService().register_question(+ "path-1",+ pending,+ session_id="session-1",+ turn_id="turn-2",+ )+ ask_user = {"questions": [{"id": "stable-question", "prompt": "Which colour?"}]}+ capability = MasteryLoopCapability()++ await capability.on_user_pause(_context(), ask_user)+ await capability.on_user_resume(+ _context(), ask_user, reply_text="选B", answers=None+ )++ answered = LearningStore().get_interaction("path-1", "stable-question")+ assert answered is not None+ assert answered.status == InteractionStatus.ANSWERED+ assert answered.user_answer == "选B"++@pytest.mark.asyncioasync def test_hooks_bind_to_the_open_interaction_not_the_card_id(tmp_path, monkeypatch):"""A same-round mastery_quiz + ask_user leaves the model's id on the card.