DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge PR #1943: preserve grouped questions through reviewed outline revisions
Bingxi Zhao (Frank)59cdd811705e
diff --cc deeptutor/capabilities/mastery/loop.pyindex aa5037814,5d3c8c984..17e45dca7--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@@ -147,6 -159,22 +159,22 @@@ def _looks_like_plain_choice_quiz(textreturn len(labels) >= 3 and any(_PLAIN_QUIZ_PROMPT_RE.search(line) for line in prompt_lines)+ def _looks_like_multipart_assessment(text: str) -> bool:+ prose = _QUOTED_CARD_TEXT_RE.sub(" ", text)+ if not _MULTIPART_INTENT_RE.search(prose):+ return False+ # Markdown frequently puts the title on the numbered line and the actual+ # question in the following paragraph. Count question-bearing blocks, not+ # only same-line stems; quoted/code examples were removed above.+ starts = list(_NUMBERED_QUESTION_RE.finditer(prose))+ questions = 0+ for index, start in enumerate(starts):+ end = starts[index + 1].start() if index + 1 < len(starts) else len(prose)- if re.search(r"[??]", prose[start.end():end]):++ if re.search(r"[??]", prose[start.end() : end]):+ questions += 1+ return questions >= 2++def _turn_has_graded(context: UnifiedContext) -> bool:"""Whether a ruling was made this turn, by the model or by the runtime.@@@ -277,50 -305,10 +305,55 @@@ class MasteryLoopCapabilityupdated["_mastery_session_mode"] = context.metadata.get("mastery_session_mode")updated["_session_id"] = str(context.session_id or "").strip()updated["_turn_id"] = str(context.metadata.get("turn_id") or "").strip()+ if tool_name == "mastery_profile":+ updated["_learner_message"] = context.user_message or ""+ selection = int(state.get("profile_selection", 0)) + 1+ state["profile_selection"] = selection+ state["profile_write_pending"] = True++ def profile_recorded(receipt):+ if (+ state.get("profile_selection") == selection+ and context.metadata.get("mastery_path_id") == path_id+ ):+ state["profile_write_pending"] = False+ state["profile_receipt"] = receipt++ updated["_profile_recorded"] = profile_recorded++ if tool_name == "mastery_note_explained":+ session_id = str(context.session_id or "").strip()+ turn_id = str(context.metadata.get("turn_id") or "").strip()++ def teaching_delivery():+ # A rebind must not let an earlier tool record teaching on+ # the new path or under another session/turn's provenance.+ if (+ str(context.metadata.get("mastery_path_id") or "").strip() != path_id+ or str(context.session_id or "").strip() != session_id+ or str(context.metadata.get("turn_id") or "").strip() != turn_id+ ):+ return None+ snapshot = context.extension("published_assistant_content").get("snapshot")+ return {+ "path_id": path_id,+ "session_id": session_id,+ "turn_id": turn_id,+ "segments": snapshot() if callable(snapshot) else (),+ }++ # Always override model-supplied private kwargs.+ updated["_teaching_delivery"] = teaching_delivery++ if tool_name == "mastery_revise":+ updated["_revision_request_id"] = str(+ context.extension("agent_loop").get("model_call_id") or ""+ )+++ if tool_name == "mastery_quiz":+ # A replacement needs a quote from the actual current learner+ # request, not a model-supplied claim about their intention.+ updated["_learner_message"] = context.user_message or ""if tool_name == "mastery_mode":# The narrowest handle on the turn for a tool that changes what# the rest of it may do — the same shape as ``_bind_active_path``@@@ -595,6 -562,34 +641,36 @@@if not isinstance(grade, dict) or not grade:return ""result = grade.get("result") if isinstance(grade.get("result"), dict) else {}+ results = result.get("results")+ if isinstance(results, list) and results:+ parts = [+ f"{item.get('question_id', '')}: "+ f"{'ungraded' if item.get('is_correct') is None else ('correct' if item.get('is_correct') else 'incorrect')}; "+ f"objective {item.get('knowledge_point_id', '')}; "+ f"mastered={bool(item.get('mastered'))}"+ for item in results+ if isinstance(item, dict)+ ]+ complete = result.get("complete", grade.get("complete", True)) is not False+ status = (+ "The question group was already graded by the engine. "- if complete else- "Only the submitted group replies were graded by the engine. "++ if complete++ else "Only the submitted group replies were graded by the engine. "+ "These children remain unanswered: "- + ", ".join(result.get("remaining_question_ids", [])) + ". "++ + ", ".join(result.get("remaining_question_ids", []))++ + ". "+ "Preserve unanswered children and continue at the requested pace. "+ "Explain reported gaps, but never infer confusion from an unanswered "+ "item or invent its reply. "+ )+ return (- "[Mastery] " + status +- "Do not grade it again or repeat its answer keys. Each result belongs "++ "[Mastery] "++ + status++ + "Do not grade it again or repeat its answer keys. Each result belongs "+ "only to its own objective; the parent group gives no extra credit. "+ "Address the specific gap, then use the fresh status for the next step.\n"+ + "\n".join(parts)+ )verdict = "correct" if grade.get("is_correct") else "incorrect"learner_answer = str(result.get("learner_answer") or "").strip()lines = [diff --cc deeptutor/capabilities/mastery/prompts/en/mastery_loop.yamlindex 6517a2cdd,29a551c78..ea88d36f4--- a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml@@@ -87,9 -86,10 +87,12 @@@ session# Teaching strategy. Kept separate from the loop protocol above: that one says# how a round runs, this one says what to do about the objective in front of you.playbook: |-+ **Durable teaching feedback:** Read advisory `teaching_guidance` and current-objective `teaching_focus`, alongside `learner_profile.teaching_preferences` and the current objective's `teaching_observations` in the fresh snapshot. Honor the learner's current explicit request over older style notes. On repeated confusion or an unsuccessful explanation, change the useful teaching approach (example, prerequisite, spatial explanation or suitable original figure), rather than only promising to simplify. Do not label a learner globally from one difficulty. Record important explicit requests and objective-local attempts with keyed `mastery_profile.teaching_updates` and the current `path_revision`; preserve other keys. Inferred difficulties stay `tentative`; a strategy result stays `unknown` until a learner statement or response supports `helped` or `not_helped`. Teaching, silence and unanswered cards do not prove understanding. These notes never award mastery or override source rules. Do not create a feedback tool call for every message; combine meaningful changes, and keep ordinary tutoring fluent. The learner may inspect, correct or remove these notes through conversation.+ In teaching_updates, evidence must quote the current learner message literally; a paraphrase or your own teaching text cannot confirm a strategy result. To inspect or correct older notes outside the current objective, use mastery_status with include_teaching_history=true; ordinary teaching uses the small default snapshot.+ **Source-grounded visual study:** Honor explanation, practice and review as explicit learner choices; explain untaught prerequisites at the requested level before assessment. Use `mastery_note_explained` only after the explanation was publicly delivered in this turn, with an exact `explanation_quote`; never record a future plan, private source text or reasoning. This records a partially explained slice, not complete-objective coverage, understanding or mastery credit. Historical teaching records without delivery references remain unverified, not evidence that every part was taught. An outline is never evidence of teaching. A concise explanation-only turn may end without a quiz; explicit deferral uses `mastery_defer_objective` and does not claim mastery.+ **Incremental group replies:** A learner may answer only some children. Pass those real answers to `mastery_grade`, preserve unanswered siblings, and read `complete` / `remaining_question_ids` before claiming the whole group is finished. Do not ask for already graded answers again.+ **Registered grouped practice:** When the learner requests questions together, use `mastery_quiz.questions` for a bounded group of two to four separately answerable memory/procedure questions. Each item must name a real objective and carry its own supported question and private answer contract; do not concatenate expected answers or pose official numbered assessments in prose. A group is one active interaction with separate results, not extra mastery credit. If an unrelated older question is still pending, explain that briefly. Replace it only for an explicit current learner request, using `pending_action: replace`, the fresh `replace_question_id`, and `replacement_request` as a literal quote from that request. Otherwise retain it. Never infer abandonment from silence or a pacing preference. Do not call the single-question tool twice and promise two cards. Unsupported objective types still use their native qualitative assessment path. When an existing registered card should be shown again, call mastery_quiz with pending_action: resume and its exact current parent resume_question_id, omitting new-question and replacement arguments. This re-presents the stored card; it does not replace it or award credit. Do not reconstruct pending questions as a prose list.+ **Concise but explanatory:** Do not replace teaching with a list of names, priority labels or compressed definitions. At the learner's requested level, explain the necessary meaning and one useful connection or concrete example before assessing it. After feedback that an explanation was too terse, supply the missing link rather than another equally compressed formulation. Split useful teaching into connected steps when needed; there is no fixed word quota or compulsory question after each step.- **Source-grounded visual study:** Honor explanation, practice and review as explicit learner choices; explain untaught prerequisites at the requested level before assessment. Use `mastery_note_explained` after an explanation; this records coverage without mastery credit. An outline is never evidence of teaching. A concise explanation-only turn may end without a quiz; explicit deferral uses `mastery_defer_objective` and does not claim mastery.When the goal includes figure understanding, declare the relevant objective's `required_visual_tasks` in the outline (`identification`, `relationship`, `table_graph`, `comparison`). Generic text scores do not satisfy these. Read `mastery_status.visual_requirements` and `learning_stages`; explain whether the next work addresses missing independent evidence, prior difficulty or due review.Retrieve and inspect the original pixels with `rag` before a visual question. Pass `visual` to `mastery_quiz`, using exact source references and a supported reference quote, plus verified equivalent terminology (including the learner's language). Ask about the actual numbered label, visible relationship, plotted/table values or supported comparison. Preserve the original and source location; do not replace it with a generated diagram or invent a masked/segmented target. A key based only on uncertain pixel interpretation stays `unverified` and ungraded.Describe visible answer cues honestly. A labeled image or direct table/page reading is guided practice; do not claim independent recall. Repeating recently assisted work is also weakened through the existing retention boundary. Unknown wording asks for clarification rather than fuzzy grading; use a well-grounded choice question when a supported wrong answer must be distinguished reliably. Explain mistakes against the original source and offer a different supported example, not an immediate loop of the same question.diff --cc deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yamlindex a39606b59,8a8e168a2..fe54ef653--- a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml@@@ -84,9 -83,10 +84,12 @@@ session# 教学策略。与 loop 协议分开:上面说的是「一轮怎么走」,这里说的是「针对这个知识点做什么」。playbook: |-+ **持久教学反馈:** 读取建议性的 `teaching_guidance` 及当前知识点的 `teaching_focus`,并读取最新状态中的 `learner_profile.teaching_preferences` 及当前知识点的 `teaching_observations`。当前明确请求优先于旧的风格偏好。反复困惑或解释未奏效时,改变教学方式(例子、前置知识、空间说明或适合的原始图),不要只承诺简化。一次困难不能给学习者贴全局标签。用带键的 `mastery_profile.teaching_updates` 和当前 `path_revision` 记录重要明确请求及知识点局部尝试,保留其他键。推测困难标为 `tentative`;只有学习者的陈述或回答支持时,才把策略结果从 `unknown` 改为 `helped` 或 `not_helped`。讲过、沉默或未回答不能证明理解;这些记录不授予掌握分,也不覆盖来源规则。无需每条消息都调用反馈工具,合并有意义的更新并保持教学流畅。学习者可通过对话查看、纠正或删除记录。+ teaching_updates 的 evidence 必须逐字引用当前学习者消息;意译或教师自己讲过的内容不能确认策略效果。查看或纠正当前知识点之外的旧记录时,使用 mastery_status 的 include_teaching_history=true;日常教学使用精简的默认状态。+ **来源扎实的视觉学习:** 尊重学习者明确选择的讲解、练习或复习,按要求的层次先解释必要前置知识。仅在本轮已经公开讲解后调用 `mastery_note_explained`,提供逐字的 `explanation_quote`;不能记录未来计划、私有来源文本或推理。它只记录部分已讲解内容,不证明整个目标已覆盖、已理解或已掌握。没有公开交付引用的历史教学记录仍未核实,不能当作全部讲过的证据;生成提纲不等于教学。仅需简洁讲解时可以不出题;明确暂缓用 `mastery_defer_objective`,不能假称已掌握。+ **分次回答组合题:** 学习者可以只回答部分子题。把这些实际回答传给 `mastery_grade`,保留尚未回答的子题,并在宣称整组已完成前检查 `complete` / `remaining_question_ids`。不要重复索取已经评分的回答。+ **已登记的组合练习**:学习者要求一起回答问题时,用 `mastery_quiz.questions` 建立二至四题的有界组合;每题独立作答,只用于 memory/procedure 知识点。每题必须指向真实知识点并保存自己的、有来源支持的题目与私密答案契约;不能把答案拼接后一起模糊判分,也不能把正式编号考核写在正文里。组合只有一个活跃交互,但结果分别归属各题,不额外授予掌握分。若仍有不相关的旧待答题,简短说明;只有学习者当前明确要求替换时,才用 `pending_action: replace`、最新 `replace_question_id` 和当前请求的逐字引用 `replacement_request` 替换,否则保留。沉默或节奏偏好不是放弃旧题的证据。不要连续调用单题工具后承诺两张卡片;不支持的知识点类型仍走原有定性考核流程。 需要再次展示已有登记题卡时,调用 mastery_quiz,只传 pending_action: resume 和最新父题 resume_question_id,不传新题契约或替换参数;这只重新展示存储题卡,不替换它也不授予掌握分。不要把待答题重新写成纯文本列表。+ **简洁但讲清楚**:不要用名称列表、重要性标签或压缩定义代替教学。按学习者需要的深度,先讲必要的含义以及一个有用联系或具体例子,再考核。学习者说解释太简略时,补上缺失的联系,不要换成同样简略的说法。需要时把教学拆成连贯小步;没有固定字数配额,也不要求每一步之后都出题。- **来源扎实的视觉学习:** 尊重学习者明确选择的讲解、练习或复习,按要求的层次先解释必要前置知识。讲解后调用 `mastery_note_explained`,只记录已讲解覆盖,不授予掌握分;生成提纲不等于教学。仅需简洁讲解时可以不出题;明确暂缓用 `mastery_defer_objective`,不能假称已掌握。目标包含原图理解时,在对应提纲目标声明 `required_visual_tasks`(identification、relationship、table_graph、comparison)。通用文字题高分不能替代这些任务。查看 `mastery_status.visual_requirements` 和 `learning_stages`,解释下一步来自缺少独立证据、此前困难还是到期复习。视觉题先通过 `rag` 读取并检查原始像素,再给 `mastery_quiz` 传 `visual`:精确来源、来源中的参考引文以及已核验的等价术语(包含学习者语言)。练习应判断真实编号标签、可见关系、图表数据或有证据支持的比较。保留原图及位置,不能用生成图替代,也不能虚构遮罩或分割目标。仅凭不确定图像理解得到的答案键标为 unverified,保留未评分。如实记录可见答案线索:带答案标签或直接读取表格/页面是辅助练习,不是独立回忆;即时重复刚获帮助的题目也会按现有复习时间边界降权。未知表述应澄清而不是模糊打分;需要可靠区分实质性错误时使用来源明确的选择题。答错后对照原图讲解,提供其他有依据的例子,不要立即循环相同问题。diff --cc deeptutor/capabilities/mastery/tools.pyindex 20919e46e,9b78d9963..b153a1bec--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@@ -821,7 -798,22 +821,23 @@@ class MasteryStatusTool(BaseTool)"question_id": interaction.interaction_id,"status": interaction.status.value,}- if interaction.status == InteractionStatus.ANSWERED:+ if interaction.question.questions:+ graded_ids = {+ result["question_id"] for result in interaction.result.get("results", [])+ }+ pending_interaction["answers"] = dict(interaction.answers)+ pending_interaction["remaining_question_ids"] = [- q.question_id for q in interaction.question.questions++ q.question_id++ for q in interaction.question.questions+ if q.question_id not in graded_ids+ ]+ pending_interaction["instruction"] = (+ "Keep committed child replies verbatim. Grade only actual replies; "+ "unanswered children remain open and earn no score. Continue at the requested "+ "pace; explain reported gaps, but never infer confusion from an unanswered "+ "item or invent a missing reply."+ )+ elif interaction.status == InteractionStatus.ANSWERED:# The answer is learner-authored state, not the hidden answer# key. Returning it lets a restart grade rather than ask twice.pending_interaction["learner_answer"] = interaction.user_answer@@@ -1141,56 -1086,92 +1189,104 @@@ class MasteryQuizTool(BaseTool)progress = _load_path(service, path_id)if progress is None:return _no_built_path_result("mastery_quiz")- scope = _review_scope_refusal(kwargs, progress, kp_id)- if scope is not None:- return scope- kp, module_id, _ = find_knowledge_point(progress, kp_id)- if kp is None:+ pending_action = kwargs.get("pending_action", "retain")+ resume_id = kwargs.get("resume_question_id")+ if pending_action == "resume":+ contract_fields = {- "knowledge_point_id", "question", "expected_answer", "question_type", "options",- "explanation", "difficulty", "visual", "questions", "replace_question_id", "replacement_request",++ "knowledge_point_id",++ "question",++ "expected_answer",++ "question_type",++ "options",++ "explanation",++ "difficulty",++ "visual",++ "questions",++ "replace_question_id",++ "replacement_request",+ }+ if (- not isinstance(resume_id, str) or not resume_id.strip()++ not isinstance(resume_id, str)++ or not resume_id.strip()+ or any(kwargs.get(field) is not None for field in contract_fields)+ ):+ return ToolResult(+ content="Resume needs only pending_action='resume' and the exact pending parent resume_question_id; omit new-question and replacement arguments.",+ success=False,+ )+ elif resume_id is not None:- return ToolResult(content="resume_question_id requires pending_action='resume'.", success=False)+ return ToolResult(- content=f"Unknown objective {kp_id!r}; call mastery_status for valid ids.",- success=False,++ content="resume_question_id requires pending_action='resume'.", success=False+ )- visual_context: dict[str, Any] = {}- accepted_answers: list[str] = []- if kwargs.get("visual") is not None:- from deeptutor.learning.visual_practice import prepare_visual-- if not isinstance(kwargs["visual"], dict):+ if pending_action == "replace":+ request = kwargs.get("replacement_request")+ learner_message = kwargs.get("_learner_message")+ if (+ not isinstance(request, str)+ or not request.strip()+ or not isinstance(learner_message, str)+ or request not in learner_message+ ):return ToolResult(- content="visual must be an object with exact source references.", success=False- )- try:- visual_context, accepted_answers = await asyncio.to_thread(- prepare_visual,- kwargs["visual"],- expected_answer=expected,- options={option["label"]: option["body"] for option in options},- attached_kbs=kwargs.get("_attached_kb_names"),- inspected_image_hashes=kwargs.get("_inspected_image_hashes", []),- )- from deeptutor.learning.visual_practice import account_for_recent_assistance-- visual_context = account_for_recent_assistance(- visual_context, progress.quiz_attempts, kp_id+ content="Replacement needs a literal request from the current learner message.",+ success=False,)- except (OSError, ValueError, TypeError) as exc:+ raw_questions = kwargs.get("questions")+ if pending_action == "resume":+ pending, echoed_options = None, False+ elif raw_questions is None:+ built = await self._build_question(kwargs, progress)+ if isinstance(built, ToolResult):+ return built+ pending, echoed_options, kp = built+ else:+ if not isinstance(raw_questions, list) or not 2 <= len(raw_questions) <= 4:return ToolResult(- content=f"Visual practice is unavailable: {exc}. Inspect/clarify the source; no assessment was created.",+ content="questions must contain two to four independent questions.",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,- explanation=str(kwargs.get("explanation") or "").strip()[:2000],- difficulty=_normalize_difficulty(kwargs.get("difficulty")),- visual_context=visual_context,- accepted_answers=accepted_answers,- )+ fields = {+ "knowledge_point_id",+ "question",+ "expected_answer",+ "question_type",+ "options",+ "explanation",+ "difficulty",+ "visual",+ }+ leaves = []+ echoed_options = False+ for raw in raw_questions:+ if (+ not isinstance(raw, dict)+ or set(raw) - fields+ or not {"knowledge_point_id", "question", "expected_answer"} <= set(raw)+ ):+ return ToolResult(+ content="Group leaves must use the single-question contract, without nested groups.",+ success=False,+ )+ built = await self._build_question(+ {**{key: value for key, value in kwargs.items() if key.startswith("_")}, **raw},+ progress,+ )+ if isinstance(built, ToolResult):+ return built+ question, echoed, kp = built+ leaves.append(question)+ echoed_options = echoed_options or echoed+ try:+ pending = PendingQuestion(+ question_id=uuid.uuid4().hex,+ knowledge_point_id=leaves[0].knowledge_point_id,+ module_id=leaves[0].module_id,+ prompt=str(kwargs.get("question") or ""),+ question_type="group",+ questions=leaves,+ )+ except ValueError as exc:+ return ToolResult(content=str(exc), success=False)from deeptutor.learning.service import MasteryInteractionErrortry:@@@ -1278,10 -1268,109 +1383,123 @@@"their own words and record that with mastery_assess.")- return ToolResult(- content=notice,- metadata={"mastery_quiz": payload, QUESTION_CARD_KEY: card},+ metadata = {"mastery_quiz": payload, QUESTION_CARD_KEY: card}+ if pending_action == "resume" and pending.questions and interaction.result.get("results"):+ # The original grade message may be outside the current history+ # page. Reuse its public cumulative receipt to restore leaf locks;+ # this is a replay, never another grading call or mastery credit.+ result = {- key: interaction.result[key] for key in (- "question_id", "question_type", "complete", "remaining_question_ids",- "is_correct", "result",- ) if key in interaction.result++ key: interaction.result[key]++ for key in (++ "question_id",++ "question_type",++ "complete",++ "remaining_question_ids",++ "is_correct",++ "result",++ )++ if key in interaction.result+ }+ leaf_fields = {- "question_id", "knowledge_point_id", "is_correct", "learner_answer",- "correct_label", "correct_body", "explanation", "result", "independent", "diagnosis",++ "question_id",++ "knowledge_point_id",++ "is_correct",++ "learner_answer",++ "correct_label",++ "correct_body",++ "explanation",++ "result",++ "independent",++ "diagnosis",+ }+ result["results"] = [+ {key: value for key, value in leaf.items() if key in leaf_fields}+ for leaf in interaction.result["results"]+ ]+ metadata["mastery_grade"] = {+ "question_id": pending.question_id,+ "question_type": "group",+ "complete": False,+ "remaining_question_ids": interaction.result.get("remaining_question_ids", []),+ "replayed": True,+ "result": result,+ }+ return ToolResult(content=notice, metadata=metadata)++ async def _build_question(self, kwargs, progress):+ 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,+ )+ try:+ q_type, options, expected = _normalize_quiz_contract(+ kwargs.get("question_type"), kwargs.get("options"), expected+ )+ except ValueError as exc:+ return ToolResult(content=str(exc), success=False)++ question, echoed_options = strip_echoed_options(+ question, {option["label"]: option["body"] for option in options}+ )++ if q_type == "choice":+ options, expected = _shuffle_choice_options(options, expected, random.Random())++ scope = _review_scope_refusal(kwargs, progress, kp_id)+ if scope is not None:+ return scope+ 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,+ )+ visual_context: dict[str, Any] = {}+ accepted_answers: list[str] = []+ if kwargs.get("visual") is not None:+ from deeptutor.learning.visual_practice import prepare_visual++ if not isinstance(kwargs["visual"], dict):+ return ToolResult(+ content="visual must be an object with exact source references.", success=False+ )+ try:+ visual_context, accepted_answers = await asyncio.to_thread(+ prepare_visual,+ kwargs["visual"],+ expected_answer=expected,+ options={option["label"]: option["body"] for option in options},+ attached_kbs=kwargs.get("_attached_kb_names"),+ inspected_image_hashes=kwargs.get("_inspected_image_hashes", []),+ )+ from deeptutor.learning.visual_practice import account_for_recent_assistance++ visual_context = account_for_recent_assistance(+ visual_context, progress.quiz_attempts, kp_id+ )+ except (OSError, ValueError, TypeError) as exc:+ return ToolResult(+ content=f"Visual practice is unavailable: {exc}. Inspect/clarify the source; no assessment was created.",+ 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,+ explanation=str(kwargs.get("explanation") or "").strip()[:2000],+ difficulty=_normalize_difficulty(kwargs.get("difficulty")),+ visual_context=visual_context,+ accepted_answers=accepted_answers,)+ return pending, echoed_options, kpclass MasteryGradeTool(BaseTool):diff --cc deeptutor/learning/service.pyindex 7435499d1,98e7c4cb9..5c8938c05--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@@ -665,6 -668,14 +668,18 @@@ class LearningServiceexisting interaction instead of overwriting its expected answer."""+ if pending_action not in {"retain", "replace", "resume"}:+ raise MasteryInteractionError("pending_action must be retain, replace or resume")+ if pending_action == "resume":+ if pending is not None or replace_question_id or not resume_question_id:- raise MasteryInteractionError("Resume needs only the exact pending parent question_id")++ raise MasteryInteractionError(++ "Resume needs only the exact pending parent question_id"++ )+ elif pending is None or resume_question_id:- raise MasteryInteractionError("A new question contract cannot include resume_question_id")++ raise MasteryInteractionError(++ "A new question contract cannot include resume_question_id"++ )+def register(tx):active = tx.active_interaction()if active is None:@@@ -686,21 -697,67 +701,77 @@@active = persistedelse:tx.put_interaction(active)- if active is not None:+ if pending_action == "resume":+ if active is None or active.interaction_id != resume_question_id:+ raise StaleInteractionError(+ resume_question_id, active.interaction_id if active else ""+ )+ if active.status not in {- InteractionStatus.REGISTERED, InteractionStatus.AWAITING_INPUT,++ InteractionStatus.REGISTERED,++ InteractionStatus.AWAITING_INPUT,+ }:- raise MasteryInteractionError("This question is no longer awaiting input; refresh mastery_status")++ raise MasteryInteractionError(++ "This question is no longer awaiting input; refresh mastery_status"++ )++ graded_ids = {+ result["question_id"] for result in (active.result or {}).get("results", [])+ }+ if set(active.answers) - graded_ids:+ raise MasteryInteractionError(+ "Grade the committed answers before re-presenting the remaining card"+ )- known_ids = {kp.id for module in tx.progress.modules for kp in module.knowledge_points}++ known_ids = {++ kp.id for module in tx.progress.modules for kp in module.knowledge_points++ }+ for question in active.question.questions or [active.question]:- if question.question_id not in graded_ids and question.knowledge_point_id not in known_ids:- raise MasteryInteractionError("The pending objective changed; refresh mastery_status")++ if (++ question.question_id not in graded_ids++ and question.knowledge_point_id not in known_ids++ ):++ raise MasteryInteractionError(++ "The pending objective changed; refresh mastery_status"++ )+ return active, False+ if active is not None and pending_action == "retain":+ if bool(pending.questions) != bool(active.question.questions):+ raise MasteryInteractionError(+ "An incompatible question is already pending; retain it or explicitly "+ "replace its question_id before creating a group"+ )+ if pending.questions and self._group_contract(pending) != self._group_contract(+ active.question+ ):+ raise MasteryInteractionError(+ "A different group is already pending; explicitly replace its question_id"+ )return active, False+ if pending_action == "replace" and (+ active is None or active.interaction_id != replace_question_id+ ):+ raise StaleInteractionError(+ replace_question_id, active.interaction_id if active else ""+ )- known_kp = next(- (- kp- for module in tx.progress.modules- for kp in module.knowledge_points- if kp.id == pending.knowledge_point_id- ),- None,- )- if known_kp is None:- raise MasteryInteractionError(- f"Unknown objective {pending.knowledge_point_id!r}; refresh mastery_status"+ leaves = pending.questions or [pending]+ known_ids = {kp.id for module in tx.progress.modules for kp in module.knowledge_points}+ for question in leaves:+ if question.knowledge_point_id not in known_ids:+ raise MasteryInteractionError(+ f"Unknown objective {question.knowledge_point_id!r}; refresh mastery_status"+ )+ if active is not None:+ active.status = InteractionStatus.ABANDONED+ tx.put_interaction(active)+ tx.emit(+ "interaction.abandoned",+ {+ "interaction_id": active.interaction_id,+ "reason": "explicit_replacement",+ "replacement_id": pending.question_id,+ },+ session_id=session_id,+ turn_id=turn_id,)interaction = MasteryInteraction(@@@ -1034,6 -1050,306 +1064,308 @@@interaction, replayed = resultreturn progress, interaction, replayed+ @staticmethod+ def _group_contract(pending: PendingQuestion) -> list[tuple]:+ # Choice shuffling changes labels, not the answer contract. Ignore new+ # generated ids when a duplicate tool call re-presents the same group.+ return [+ (+ q.knowledge_point_id,+ q.prompt,+ q.question_type,+ tuple(sorted(q.choice_map.values())),+ q.choice_map.get(q.expected_answer, q.expected_answer),+ q.explanation,+ q.difficulty,+ q.visual_context,+ )+ for q in pending.questions+ ]++ @staticmethod+ def _validate_group_answers(pending: PendingQuestion, answers: Any) -> dict[str, str]:+ ids = {question.question_id for question in pending.questions}+ if (+ not isinstance(answers, dict)+ or not answers+ or not set(answers).issubset(ids)+ or any(+ not isinstance(value, str) or not value.strip() or len(value) > 10000+ for value in answers.values()+ )+ ):+ raise MasteryInteractionError(+ "Supply at least one actual answer using its exact group question_id"+ )+ from deeptutor.learning.pending import resolve_choice_submission++ for question in pending.questions:+ if (+ question.question_id in answers+ and question.question_type == "choice"- and not resolve_choice_submission(answers[question.question_id], question.choice_map)++ and not resolve_choice_submission(++ answers[question.question_id], question.choice_map++ )+ ):+ raise MasteryInteractionError(+ "Choose one unambiguous option for each choice question"+ )+ return {key: value.strip() for key, value in answers.items()}++ def _merge_group_answers(self, interaction: MasteryInteraction, answers: Any) -> dict[str, str]:+ submitted = self._validate_group_answers(+ interaction.question, interaction.answers if answers is None else answers+ )+ if any(+ key in interaction.answers and interaction.answers[key] != value+ for key, value in submitted.items()+ ):+ raise MasteryInteractionError("This group already has a different committed answer")+ return {**interaction.answers, **submitted}++ @staticmethod+ def _group_result(pending: PendingQuestion, results: list[dict]) -> dict:+ values = [result["is_correct"] for result in results]+ graded_ids = {result["question_id"] for result in results}+ remaining = [q.question_id for q in pending.questions if q.question_id not in graded_ids]+ complete = not remaining+ return {+ "question_id": pending.question_id,+ "question_type": "group",+ "results": results,+ "complete": complete,+ "remaining_question_ids": remaining,+ "is_correct": None if not complete or None in values else all(values),+ "result": "ungraded"+ if not complete or all(value is None for value in values)+ else "mixed"+ if len(set(values)) > 1+ else "correct"+ if all(values)+ else "incorrect",+ }++ def _grade_group(+ self,+ tx,+ interaction: MasteryInteraction,+ *,+ answers,+ scheduler=None,+ session_id="",+ turn_id="",+ ) -> tuple[MasteryInteraction, bool]:+ """Commit new replies once; unanswered siblings remain awaiting input."""+ pending = interaction.question+ submitted = self._merge_group_answers(interaction, answers)+ known_ids = {kp.id for module in tx.progress.modules for kp in module.knowledge_points}+ if any(q.knowledge_point_id not in known_ids for q in pending.questions):+ raise MasteryInteractionError("An objective changed; refresh the question group")+ from deeptutor.learning.question_card import build_grade_result++ leaves = []+ for question in pending.questions:+ if question.question_id not in submitted:+ continue+ stored = tx.get_interaction(question.question_id)+ if stored is not None and (+ stored.result.get("group_question_id") != pending.question_id+ or stored.question.knowledge_point_id != question.knowledge_point_id+ or stored.user_answer != submitted[question.question_id]+ ):+ raise MasteryInteractionError("This child belongs to another interaction or reply")+ leaves.append((question, stored))++ results = []+ new_results = False+ for question, stored in leaves:+ if stored is not None and stored.status == InteractionStatus.GRADED:+ results.append(self._group_leaf_result(stored))+ continue+ new_results = True+ leaf = MasteryInteraction(+ interaction_id=question.question_id,+ path_id=interaction.path_id,+ question=question,+ status=InteractionStatus.ANSWERED,+ user_answer=submitted[question.question_id],+ )+ raw, correct, visual_result, diagnosis = self._evaluate_question(+ tx,+ leaf,+ answer=submitted[question.question_id],+ scheduler=scheduler,+ session_id=session_id,+ turn_id=turn_id,+ )+ result = build_grade_result(+ question_id=question.question_id,+ is_correct=bool(correct),+ learner_answer=raw,+ correct_label=question.expected_answer if correct is not None else "",+ choice_options=question.choice_map,+ explanation=question.explanation if correct is not None else diagnosis,+ result=visual_result,+ independent=not bool(question.visual_context.get("hints_used"))+ if question.visual_context+ else None,+ )+ result["is_correct"] = correct+ result["knowledge_point_id"] = question.knowledge_point_id+ if diagnosis:+ result["diagnosis"] = diagnosis+ results.append(result)+ leaf.session_id = session_id or interaction.session_id+ leaf.turn_id = turn_id or interaction.turn_id+ leaf.status = InteractionStatus.GRADED+ leaf.result = {**result, "group_question_id": pending.question_id}+ tx.put_interaction(leaf)+ tx.emit(+ "practice.ungraded" if correct is None else "attempt.recorded",+ {+ "interaction_id": interaction.interaction_id,+ "question_id": question.question_id,+ "knowledge_point_id": question.knowledge_point_id,+ "is_correct": correct,+ },+ session_id=session_id,+ turn_id=turn_id,+ )+ if correct is not None:+ evidence = tx.progress.learning_evidence[-1]+ tx.emit(+ "evidence.recorded",+ {+ "knowledge_point_id": evidence.knowledge_point_id,+ "assessment_type": evidence.assessment_type,+ "result": evidence.result,+ "quality": evidence.quality,+ },+ session_id=session_id,+ turn_id=turn_id,+ )+ if not new_results:+ return interaction, True+ interaction.result = self._group_result(pending, results)+ complete = interaction.result["complete"]+ interaction.status = (+ InteractionStatus.GRADED if complete else InteractionStatus.AWAITING_INPUT+ )+ interaction.answers = submitted+ interaction.session_id = session_id or interaction.session_id+ interaction.turn_id = turn_id or interaction.turn_id+ if complete:+ tx.progress.pending_question = None+ tx.put_interaction(interaction)+ tx.emit(+ "interaction.graded" if complete else "interaction.partially_graded",+ dict(interaction.result),+ session_id=interaction.session_id,+ turn_id=interaction.turn_id,+ )+ return interaction, False++ def _evaluate_question(+ self,+ tx,+ interaction: MasteryInteraction,+ *,+ answer: str,+ answer_for_grading: str | None = None,+ expected_answer: str | None = None,+ resolved_choice_options: dict[str, str] | None = None,+ scheduler: SpacedRepetitionScheduler | None = None,+ session_id: str = "",+ turn_id: str = "",+ ) -> tuple[str, bool | None, str, str]:+ """Shared leaf grader: never creates a parent attempt or commits separately."""+ pending = interaction.question+ 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,+ resolve_choice_submission,+ )++ option_map = pending.choice_map+ 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 = stored+ if has_option_bodies(option_map):+ graded_answer = resolve_choice_submission(raw_answer, option_map) or raw_answer+ else:+ # Legacy questions may need option bodies recovered by+ # the trusted tool adapter from the original turn.+ graded_answer = raw_answer if answer_for_grading is None else answer_for_grading+ else:+ raw_answer = stored+ graded_answer = raw_answer+ else:+ graded_answer = raw_answer if answer_for_grading is None else answer_for_grading+ authoritative_answer = (+ pending.expected_answer if expected_answer is None else expected_answer+ )+ if pending.question_type == "choice" and resolved_choice_options:+ # Bodies recovered for a legacy question (see the tool+ # adapter): store them in the structured form so nothing has+ # to recover them again.+ pending.options = [+ PendingOption(label=label, body=body)+ for label, body in resolved_choice_options.items()+ ]+ pending.expected_answer = authoritative_answer+ interaction.question = pending+ visual_result = ""+ visual_diagnosis = ""+ if pending.visual_context:+ from deeptutor.learning.visual_practice import (+ account_for_recent_assistance,+ evaluate_visual,+ )++ pending.visual_context = account_for_recent_assistance(+ pending.visual_context, tx.progress.quiz_attempts, pending.knowledge_point_id+ )+ visual_result, visual_diagnosis = evaluate_visual(pending, raw_answer)+ if (+ tx.progress.explained_objectives.get(pending.knowledge_point_id, {}).get(+ "timestamp", 0+ )+ > pending.created_at+ ):+ pending.visual_context["hints_used"] = max(+ 1, pending.visual_context.get("hints_used", 0)+ )+ pending.visual_context["teaching_after_question"] = True+ if visual_result == "correct":+ graded_answer = authoritative_answer+ is_correct = (+ None+ if visual_result == "ungraded"+ else self._apply_grade(+ tx.progress,+ question_id=pending.question_id,+ knowledge_point_id=pending.knowledge_point_id,+ module_id=pending.module_id,+ user_answer=graded_answer,+ expected_answer=authoritative_answer,+ question_type=pending.question_type,+ scheduler=scheduler,+ session_id=session_id,+ turn_id=turn_id,+ visual_context=pending.visual_context,+ )+ )+ return raw_answer, is_correct, visual_result, visual_diagnosis+def replace_modules_for_path(self,book_id: str,@@@ -1063,173 -1379,156 +1395,195 @@@edits that already carry durable IDs. Position never establishes identity."""- def replace(tx):- if name.strip() and not tx.progress.name.strip():- tx.progress.name = name.strip()[:_MAX_PATH_NAME_LEN]- applied_modules = [module.model_copy(deep=True) for module in modules]- identity_map: dict[str, list[str] | str] = {- "mode": "append" if append else ("fresh" if fresh_identity else identity_mode),- "preserved": [],- "minted": [],- "dropped": [],- }- if append:+ progress, _ = self._store.mutate(+ book_id,+ lambda tx: self._replace_module_set(+ tx,+ modules,+ append=append,+ name=name,+ event_type=event_type,+ session_id=session_id,+ turn_id=turn_id,+ identity_mode=identity_mode,+ relation_refs=relation_refs,+ source_aliases=source_aliases,+ topic_sources=topic_sources,+ fresh_identity=fresh_identity,+ ),+ create=True,+ )+ return progress++ def _replace_module_set(+ self,+ tx,+ modules: list[LearningModule],+ *,+ append: bool = False,+ name: str = "",+ event_type: str = "path.modules_replaced",+ session_id: str = "",+ turn_id: str = "",+ identity_mode: str = "explicit",+ relation_refs: dict[str, RelationRefs] | None = None,+ source_aliases: dict[str, str] | None = None,+ topic_sources: list[TopicSource] | None = None,+ fresh_identity: bool = False,+ dry_run: bool = False,+ ) -> dict[str, Any]:+ """Shared identity, relation and question effects for preview and save."""++ active_interaction_removed = False+ book_id = tx.progress.book_id+ if name.strip() and not tx.progress.name.strip():+ tx.progress.name = name.strip()[:_MAX_PATH_NAME_LEN]+ applied_modules = [module.model_copy(deep=True) for module in modules]+ identity_map: dict[str, list[str] | str] = {+ "mode": "append" if append else ("fresh" if fresh_identity else identity_mode),+ "preserved": [],+ "minted": [],+ "dropped": [],+ }+ if append:+ reserved = _reserved_objective_ids(tx.progress)+ offset = len(tx.progress.modules)+ minted: list[str] = []+ for index, module in enumerate(applied_modules, start=offset):+ module.id = f"{book_id}_m{index}"+ module.order = index+ for kp_index, kp in enumerate(module.knowledge_points):+ kp.module_id = module.id+ candidate = f"{module.id}_kp{kp_index}"+ if candidate in reserved:+ kp.id = _new_objective_id(module.id, reserved)+ else:+ kp.id = candidate+ reserved.add(candidate)+ tx.progress.knowledge_types[kp.id] = kp.type+ minted.append(kp.id)+ identity_map["minted"] = minted+ existing_modules = tx.progress.modules+ self._resolve_final_relations(+ applied_modules,+ modules,+ relation_refs or {},+ source_aliases or {},+ tx.topic_sources() if topic_sources is None else topic_sources,+ existing_modules=existing_modules,+ )+ validate_objective_relations(+ [*existing_modules, *applied_modules],+ tx.topic_sources() if topic_sources is None else topic_sources,+ )+ tx.progress.modules.extend(applied_modules)+ if not tx.progress.current_module_id and applied_modules:+ tx.progress.current_module_id = applied_modules[0].id+ tx.progress.current_kp_index = 0+ else:+ current_kp_id = ""+ for current_module in tx.progress.modules:+ if current_module.id != tx.progress.current_module_id:+ continue+ if 0 <= tx.progress.current_kp_index < len(current_module.knowledge_points):+ current_kp_id = current_module.knowledge_points[tx.progress.current_kp_index].id+ break+ pending_kp_id = (+ tx.progress.pending_question.knowledge_point_id+ if tx.progress.pending_question is not None+ else ""+ )+ active_interaction = tx.active_interaction()+ active_kp_id = (+ active_interaction.question.knowledge_point_id+ if active_interaction is not None+ else ""+ )++ if fresh_identity:reserved = _reserved_objective_ids(tx.progress)- offset = len(tx.progress.modules)- minted: list[str] = []- for index, module in enumerate(applied_modules, start=offset):- module.id = f"{book_id}_m{index}"- module.order = index- for kp_index, kp in enumerate(module.knowledge_points):+ for module in applied_modules:+ for kp in module.knowledge_points:+ kp.id = _new_objective_id(module.id, reserved)kp.module_id = module.id- candidate = f"{module.id}_kp{kp_index}"- if candidate in reserved:- kp.id = _new_objective_id(module.id, reserved)- else:- kp.id = candidate- reserved.add(candidate)- tx.progress.knowledge_types[kp.id] = kp.type- minted.append(kp.id)- identity_map["minted"] = minted- existing_modules = tx.progress.modules- self._resolve_final_relations(- applied_modules,- modules,- relation_refs or {},- source_aliases or {},- tx.topic_sources() if topic_sources is None else topic_sources,- existing_modules=existing_modules,- )- validate_objective_relations(- [*existing_modules, *applied_modules],- tx.topic_sources() if topic_sources is None else topic_sources,+ identity_map["minted"] = [+ kp.id for module in applied_modules for kp in module.knowledge_points+ ]+ identity_map["dropped"] = sorted(+ {kp.id for module in tx.progress.modules for kp in module.knowledge_points})- tx.progress.modules.extend(applied_modules)- if not tx.progress.current_module_id and applied_modules:- tx.progress.current_module_id = applied_modules[0].id- tx.progress.current_kp_index = 0else:- current_kp_id = ""- for current_module in tx.progress.modules:- if current_module.id != tx.progress.current_module_id:- continue- if 0 <= tx.progress.current_kp_index < len(current_module.knowledge_points):- current_kp_id = current_module.knowledge_points[- tx.progress.current_kp_index- ].id- break- pending_kp_id = (- tx.progress.pending_question.knowledge_point_id- if tx.progress.pending_question is not None- else ""- )- active_interaction = tx.active_interaction()- active_kp_id = (- active_interaction.question.knowledge_point_id- if active_interaction is not None- else ""- )-- if fresh_identity:- reserved = _reserved_objective_ids(tx.progress)- for module in applied_modules:- for kp in module.knowledge_points:- kp.id = _new_objective_id(module.id, reserved)- kp.module_id = module.id- identity_map["minted"] = [- kp.id for module in applied_modules for kp in module.knowledge_points- ]- identity_map["dropped"] = sorted(- {kp.id for module in tx.progress.modules for kp in module.knowledge_points}- )- else:- identity_map = assign_objective_identities(- tx.progress,- applied_modules,- identity_mode=identity_mode,- )- sources = tx.topic_sources() if topic_sources is None else topic_sources- self._resolve_final_relations(+ identity_map = assign_objective_identities(+ tx.progress,applied_modules,- modules,- relation_refs or {},- source_aliases or {},- sources,+ identity_mode=identity_mode,)- validate_objective_relations(applied_modules, sources)- self.replace_modules(tx.progress, applied_modules)- objective_locations = {- kp.id: (module.id, kp_index)- for module in applied_modules- for kp_index, kp in enumerate(module.knowledge_points)- }+ sources = tx.topic_sources() if topic_sources is None else topic_sources+ self._resolve_final_relations(+ applied_modules,+ modules,+ relation_refs or {},+ source_aliases or {},+ sources,+ )+ validate_objective_relations(applied_modules, sources)+ self.replace_modules(tx.progress, applied_modules)+ objective_locations = {+ kp.id: (module.id, kp_index)+ for module in applied_modules+ for kp_index, kp in enumerate(module.knowledge_points)+ }++ if current_kp_id in objective_locations:+ (+ tx.progress.current_module_id,+ tx.progress.current_kp_index,+ ) = objective_locations[current_kp_id]+ elif applied_modules:+ tx.progress.current_module_id = applied_modules[0].id+ tx.progress.current_kp_index = 0+ else:+ tx.progress.current_module_id = ""+ tx.progress.current_kp_index = 0- if current_kp_id in objective_locations:- (- tx.progress.current_module_id,- tx.progress.current_kp_index,- ) = objective_locations[current_kp_id]- elif applied_modules:- tx.progress.current_module_id = applied_modules[0].id- tx.progress.current_kp_index = 0+ if tx.progress.pending_question is not None:- if pending_kp_id not in objective_locations:++ pending_leaves = tx.progress.pending_question.questions or [++ tx.progress.pending_question++ ]++ if pending_kp_id not in objective_locations or any(++ q.knowledge_point_id not in objective_locations for q in pending_leaves++ ):+ tx.progress.pending_question = Noneelse:- pending_module_id, _ = objective_locations[pending_kp_id]- tx.progress.pending_question.module_id = pending_module_id- tx.progress.current_module_id = ""- tx.progress.current_kp_index = 0-- if tx.progress.pending_question is not None:- pending_leaves = tx.progress.pending_question.questions or [- tx.progress.pending_question- ]- if pending_kp_id not in objective_locations or any(- q.knowledge_point_id not in objective_locations for q in pending_leaves- ):- tx.progress.pending_question = None- else:- pending_module_id, _ = objective_locations[pending_kp_id]- tx.progress.pending_question.module_id = pending_module_id- for question in pending_leaves:- question.module_id = objective_locations[question.knowledge_point_id][0]-- if active_interaction is not None:- active_leaves = active_interaction.question.questions or [- active_interaction.question- ]- if active_kp_id not in objective_locations or any(- q.knowledge_point_id not in objective_locations for q in active_leaves- ):++ tx.progress.pending_question.module_id = objective_locations[pending_kp_id][0]++ for question in pending_leaves:++ question.module_id = objective_locations[question.knowledge_point_id][0]++ if active_interaction is not None:- if active_kp_id not in objective_locations:++ active_leaves = active_interaction.question.questions or [++ active_interaction.question++ ]++ active_interaction_removed = active_kp_id not in objective_locations or any(++ q.knowledge_point_id not in objective_locations for q in active_leaves++ )++ if active_interaction_removed:+ if not dry_run:tx.abandon_active_interactions()- else:- active_module_id, _ = objective_locations[active_kp_id]- active_changed = (- active_interaction.question.module_id != active_module_id- or any(- question.module_id- != objective_locations[question.knowledge_point_id][0]- for question in active_leaves- )+ else:- active_module_id, _ = objective_locations[active_kp_id]- if active_interaction.question.module_id != active_module_id:- active_interaction.question.module_id = active_module_id- if not dry_run:- tx.put_interaction(active_interaction)++ active_module_id = objective_locations[active_kp_id][0]++ active_changed = (++ active_interaction.question.module_id != active_module_id++ or any(++ question.module_id++ != objective_locations[question.knowledge_point_id][0]++ for question in active_leaves+ )- active_interaction.question.module_id = active_module_id- for question in active_leaves:- question.module_id = objective_locations[question.knowledge_point_id][0]- if active_changed:- tx.put_interaction(active_interaction)++ )++ active_interaction.question.module_id = active_module_id++ for question in active_leaves:++ question.module_id = objective_locations[question.knowledge_point_id][0]++ if active_changed and not dry_run:++ tx.put_interaction(active_interaction)+ if not dry_run:tx.touch()tx.emit(event_type,@@@ -1244,125 -1543,9 +1598,121 @@@session_id=session_id,turn_id=turn_id,)+ return {+ "identity_map": identity_map,- "active_interaction_removed": bool(- active_kp_id and active_kp_id not in objective_locations- )- if not append- else False,++ "active_interaction_removed": active_interaction_removed,+ }- progress, _ = self._store.mutate(book_id, replace, create=True)- return progress+ def preview_module_revision(+ self,+ book_id: str,+ modules: list[LearningModule],+ *,+ expected_revision: int,+ session_id: str,+ request_id: str = "",+ ) -> tuple[dict[str, Any], LearningProgress]:+ """Run the real replacement engine on a copy, then record the reviewed draft."""+ from deeptutor.learning.outline_revision import exact_diff, state_digest+ from deeptutor.learning.storage import LearningConflictError++ with self._store.transaction(book_id) as tx:+ if tx.base_revision != expected_revision:+ raise LearningConflictError(book_id, expected_revision, tx.base_revision)+ original = tx.progress+ tx.progress = original.model_copy(deep=True)+ try:+ effects = self._replace_module_set(tx, modules, dry_run=True)+ proposed = tx.progress.model_copy(deep=True)+ finally:+ tx.progress = original+ # Save-time bookkeeping is not a curriculum change or progress reset.+ exclude = {"version", "updated_at"}+ changes = exact_diff(+ original.model_dump(mode="json", exclude=exclude),+ proposed.model_dump(mode="json", exclude=exclude),+ )+ if not changes:+ raise ValueError("This plan changes nothing. Leave the current outline in place.")+ payload = {+ "base_revision": expected_revision,+ "request_id": request_id,+ "before_digest": state_digest(original),+ "after_digest": state_digest(proposed),+ "modules": [module.model_dump(mode="json") for module in proposed.modules],+ "changes": changes,+ "effects": effects,+ "before_module_order": [module.id for module in original.modules],+ "proposed_module_order": [module.id for module in proposed.modules],+ }+ preview_id = tx.record_module_preview(payload, session_id=session_id)+ return {+ "preview_id": preview_id,+ "base_revision": expected_revision,+ "changes": changes,+ "effects": effects,+ "before_module_order": payload["before_module_order"],+ "proposed_module_order": payload["proposed_module_order"],+ "module_order_changed": (+ payload["before_module_order"] != payload["proposed_module_order"]+ ),+ }, proposed++ def commit_module_revision(+ self,+ book_id: str,+ preview_id: int,+ *,+ session_id: str,+ turn_id: str = "",+ request_id: str = "",+ ) -> tuple[LearningProgress, dict[str, Any]]:+ """Apply only the persisted draft; stale state rolls back instead of overwriting."""+ from deeptutor.learning.outline_revision import state_digest+ from deeptutor.learning.storage import LearningConflictError++ with self._store.transaction(book_id) as tx:+ draft = tx.module_preview(preview_id, session_id=session_id)+ replayed = draft["committed_revision"] is not None+ if not replayed:+ if draft.get("request_id") and (+ not request_id or request_id == draft["request_id"]+ ):+ raise ValueError(+ "Inspect this preview in a later model round before committing it."+ )+ expected = int(draft["base_revision"])+ if expected != tx.base_revision:+ raise LearningConflictError(book_id, expected, tx.base_revision)+ if state_digest(tx.progress) != draft["before_digest"]:+ raise ValueError(+ "The outline state changed. Create and review a fresh preview."+ )+ self._replace_module_set(+ tx,+ [LearningModule.model_validate(m) for m in draft["modules"]],+ session_id=session_id,+ turn_id=turn_id,+ )+ if state_digest(tx.progress) != draft["after_digest"]:+ raise ValueError(+ "The preview no longer matches the engine result. Nothing was saved."+ )+ tx.emit(+ "path.modules_revision_committed",+ {"preview_id": preview_id},+ session_id=session_id,+ turn_id=turn_id,+ )+ receipt = {+ "preview_id": preview_id,+ "replayed": replayed,+ "applied_revision": draft["committed_revision"]+ if replayed+ else tx.base_revision + 1,+ "applied_module_order": [module["id"] for module in draft["modules"]],+ }+ return tx.progress, receiptdef create_topic(self,diff --cc tests/capabilities/test_mastery_group_delivery.pyindex 000000000,eeea364f9..4e9da4c6fmode 000000,100644..100644--- a/tests/capabilities/test_mastery_group_delivery.py+++ b/tests/capabilities/test_mastery_group_delivery.py@@@ -1,0 -1,146 +1,215 @@@+ """Numbered assessments use durable cards, including resuming partial groups."""++ import json++ import pytest++ from deeptutor.capabilities.mastery.loop import _looks_like_multipart_assessment+ from deeptutor.learning.models import (- KnowledgePoint, LearningModule, LearningProgress, PendingQuestion, KnowledgeType,++ KnowledgePoint,++ KnowledgeType,++ LearningModule,++ LearningProgress,++ PendingQuestion,+ )+ from deeptutor.learning.service import LearningService, MasteryInteractionError+ from deeptutor.learning.storage import LearningStore++[email protected]("text", [- "### 1. Topic\nWhat is alpha?\n\n### 2. Other topic\nWhat is beta?\nAnswer these numbered questions.",- "**1. First**\nWhat is alpha?\n\n**2. Second**\nWhat is beta?\nVálaszolj számozva.",- "1. What is alpha?\n2. What is beta?\nAnswer these.",-])++ "text",++ [++ "### 1. Topic\nWhat is alpha?\n\n### 2. Other topic\nWhat is beta?\nAnswer these numbered questions.",++ "**1. First**\nWhat is alpha?\n\n**2. Second**\nWhat is beta?\nVálaszolj számozva.",++ "1. What is alpha?\n2. What is beta?\nAnswer these.",++ ],++)+ def test_multiline_numbered_assessment_requires_registered_card(text):+ assert _looks_like_multipart_assessment(text)++[email protected]("text", [- "### 1. Why alpha?\nExplanation.\n### 2. Why beta?\nMore explanation.",- "> ### 1. Topic\n> What is alpha?\n> ### 2. Topic\n> What is beta?\n> Answer these.",- "```\n### 1. Topic\nWhat is alpha?\n### 2. Topic\nWhat is beta?\nAnswer these.\n```",- "1. Alpha is useful.\n2. Beta is useful.\nAnswer these later if you want.",- "### 1. What is alpha?\nVálaszolj számozva.",-])++ "text",++ [++ "### 1. Why alpha?\nExplanation.\n### 2. Why beta?\nMore explanation.",++ "> ### 1. Topic\n> What is alpha?\n> ### 2. Topic\n> What is beta?\n> Answer these.",++ "```\n### 1. Topic\nWhat is alpha?\n### 2. Topic\nWhat is beta?\nAnswer these.\n```",++ "1. Alpha is useful.\n2. Beta is useful.\nAnswer these later if you want.",++ "### 1. What is alpha?\nVálaszolj számozva.",++ ],++)+ def test_teaching_and_quoted_examples_are_not_assessments(text):+ assert not _looks_like_multipart_assessment(text)+++ @pytest.fixture+ def service(tmp_path):+ svc = LearningService(LearningStore(tmp_path))- svc.save(LearningProgress(book_id="path", modules=[LearningModule(- id="m", name="Synthetic module", order=0,- knowledge_points=[KnowledgePoint(id=key, name=key, module_id="m", type=KnowledgeType.MEMORY)- for key in ["one", "two"]],- )]))- parent = PendingQuestion(question_id="parent", knowledge_point_id="one", question_type="group",- questions=[PendingQuestion(question_id=key, knowledge_point_id=key, module_id="m",- prompt=f"Question {key}?", expected_answer="answer")- for key in ["one", "two"]])++ svc.save(++ LearningProgress(++ book_id="path",++ modules=[++ LearningModule(++ id="m",++ name="Synthetic module",++ order=0,++ knowledge_points=[++ KnowledgePoint(id=key, name=key, module_id="m", type=KnowledgeType.MEMORY)++ for key in ["one", "two"]++ ],++ )++ ],++ )++ )++ parent = PendingQuestion(++ question_id="parent",++ knowledge_point_id="one",++ question_type="group",++ questions=[++ PendingQuestion(++ question_id=key,++ knowledge_point_id=key,++ module_id="m",++ prompt=f"Question {key}?",++ expected_answer="answer",++ )++ for key in ["one", "two"]++ ],++ )+ svc.register_question("path", parent)+ svc.mark_question_awaiting("path", interaction_id="parent")+ return svc+++ def test_resume_preserves_partial_answers_results_and_credit(service):+ service.grade_interaction("path", answer="", question_id="parent", answers={"one": "answer"})+ before = service.store.load("path").model_dump()+ saved = service.store.get_active_interaction("path").model_dump()+ progress, interaction, created = service.register_question(- "path", None, pending_action="resume", resume_question_id="parent",++ "path",++ None,++ pending_action="resume",++ resume_question_id="parent",+ )+ assert not created+ assert interaction.model_dump() == saved+ assert progress.model_dump() == before+++ @pytest.mark.parametrize("question_id", ["", "unknown", "one"])+ def test_resume_rejects_noncurrent_parent_without_mutation(service, question_id):+ before = service.store.load("path").model_dump()+ with pytest.raises(MasteryInteractionError):- service.register_question("path", None, pending_action="resume", resume_question_id=question_id)++ service.register_question(++ "path", None, pending_action="resume", resume_question_id=question_id++ )+ assert service.store.load("path").model_dump() == before+++ def test_resume_rejects_answered_group_until_grade_finishes(service):- service.record_question_answer("path", "", interaction_id="parent", answers={"one": "answer", "two": "answer"})++ service.record_question_answer(++ "path", "", interaction_id="parent", answers={"one": "answer", "two": "answer"}++ )+ before = service.store.load("path").model_dump()+ with pytest.raises(MasteryInteractionError):- service.register_question("path", None, pending_action="resume", resume_question_id="parent")++ service.register_question(++ "path", None, pending_action="resume", resume_question_id="parent"++ )+ assert service.store.load("path").model_dump() == before+++ def test_resume_rejects_committed_partial_answer_until_grade_finishes(service):+ service.record_question_answer("path", "", interaction_id="parent", answers={"one": "answer"})+ before = service.store.load("path").model_dump()+ with pytest.raises(MasteryInteractionError, match="Grade the committed"):- service.register_question("path", None, pending_action="resume", resume_question_id="parent")++ service.register_question(++ "path", None, pending_action="resume", resume_question_id="parent"++ )+ assert service.store.load("path").model_dump() == before+++ @pytest.mark.asyncio+ async def test_tool_resumes_without_constructing_throwaway_question(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools+++ monkeypatch.setattr(tools, "_new_service", lambda: service)+++ async def forbidden(*args):+ raise AssertionError("Resume must not build a question or regenerate a key")+++ monkeypatch.setattr(tools.MasteryQuizTool, "_build_question", forbidden)+ service.grade_interaction("path", answer="", question_id="parent", answers={"one": "answer"})+ ended = []+ result = await tools.MasteryQuizTool().execute(- _mastery_path_id="path", pending_action="resume", resume_question_id="parent",++ _mastery_path_id="path",++ pending_action="resume",++ resume_question_id="parent",+ _end_turn_on_card=lambda: ended.append(True),+ )+ assert result.success+ card = result.metadata["mastery_question"]+ assert card["question_id"] == "parent"+ receipt = result.metadata["mastery_grade"]+ assert receipt["replayed"] and not receipt["complete"]+ assert receipt["remaining_question_ids"] == ["two"]+ assert receipt["result"]["results"][0]["learner_answer"] == "answer"+ assert ended == [True]+ assert "expected_answer" not in json.dumps(result.metadata)+ assert len(service.store.load("path").quiz_attempts) == 1+++ @pytest.mark.asyncio[email protected]("extra", [{"question": "Throwaway?"}, {"questions": []},- {"expected_answer": "secret"}, {"replace_question_id": "parent"}, {"pending_action": "retain"}])++ "extra",++ [++ {"question": "Throwaway?"},++ {"questions": []},++ {"expected_answer": "secret"},++ {"replace_question_id": "parent"},++ {"pending_action": "retain"},++ ],++)+ async def test_tool_resume_rejects_conflicting_payloads(service, monkeypatch, extra):+ from deeptutor.capabilities.mastery import tools+++ monkeypatch.setattr(tools, "_new_service", lambda: service)+ before = service.store.load("path").model_dump()- result = await tools.MasteryQuizTool().execute(**{- "_mastery_path_id": "path", "pending_action": "resume", "resume_question_id": "parent", **extra,- })++ result = await tools.MasteryQuizTool().execute(++ **{++ "_mastery_path_id": "path",++ "pending_action": "resume",++ "resume_question_id": "parent",++ **extra,++ }++ )+ assert not result.success+ assert service.store.load("path").model_dump() == before+++ @pytest.mark.asyncio+ async def test_guard_redirects_markdown_assessment_to_existing_card(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools+ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.core.context import UnifiedContext++ monkeypatch.setattr(tools, "_new_service", lambda: service)- context = UnifiedContext(user_message="Practice both", metadata={"mastery_mode": True, "mastery_path_id": "path"})++ context = UnifiedContext(++ user_message="Practice both", metadata={"mastery_mode": True, "mastery_path_id": "path"}++ )+ capability = MasteryLoopCapability()+ draft = "### 1. First\nWhat is alpha?\n### 2. Second\nWhat is beta?\nAnswer these."+ instruction = capability.finish_instruction(context, draft)+ assert "resume_question_id" in instruction- kwargs = capability.augment_kwargs("mastery_quiz", {- "pending_action": "resume", "resume_question_id": "parent",- }, context)++ kwargs = capability.augment_kwargs(++ "mastery_quiz",++ {++ "pending_action": "resume",++ "resume_question_id": "parent",++ },++ context,++ )+ result = await tools.MasteryQuizTool().execute(**kwargs)+ assert result.success+ assert result.metadata["mastery_question"]["question_id"] == "parent"+ assert capability.finish_instruction(context, "The questions are on your card.") is None+ assert service.store.load("path").quiz_attempts == []diff --cc tests/capabilities/test_mastery_question_groups.pyindex 000000000,eb3359e4e..ddcbbdc55mode 000000,100644..100644--- a/tests/capabilities/test_mastery_question_groups.py+++ b/tests/capabilities/test_mastery_question_groups.py@@@ -1,0 -1,494 +1,488 @@@+ """One durable parent, independently graded leaves, no answer-key projection."""++ import json++ from pydantic import ValidationError+ import pytest++ from deeptutor.learning.models import (+ InteractionStatus,+ KnowledgePoint,+ KnowledgeType,+ LearningModule,+ LearningProgress,+ PendingQuestion,+ )+ from deeptutor.learning.pending import public_pending_question+ from deeptutor.learning.question_card import build_question_card+ from deeptutor.learning.service import LearningService, MasteryInteractionError+ from deeptutor.learning.storage import LearningStore+++ def leaf(question_id="q1", kp_id="kp1", expected="alpha"):+ return PendingQuestion(+ question_id=question_id,+ knowledge_point_id=kp_id,+ module_id="m",+ prompt="Name this.",+ expected_answer=expected,+ explanation="PRIVATE explanation",+ )+++ def group():+ return PendingQuestion(+ question_id="g",+ knowledge_point_id="kp1",+ module_id="m",+ prompt="Two questions",+ question_type="group",+ questions=[leaf(), leaf("q2", "kp2", "beta")],+ )+++ @pytest.fixture+ def service(tmp_path):+ svc = LearningService(LearningStore(tmp_path))+ svc.save(+ LearningProgress(+ book_id="p",+ modules=[+ LearningModule(+ id="m",+ name="Module",+ order=0,+ knowledge_points=[+ KnowledgePoint(id=kp, name=kp, type=KnowledgeType.MEMORY, module_id="m")+ for kp in ["kp1", "kp2"]+ ],+ )+ ],+ )+ )+ return svc+++ def test_group_public_projection_and_reload(service):+ _, interaction, created = service.register_question("p", group())+ assert created+ reloaded = service._store.get_interaction("p", interaction.interaction_id)+ assert [q.question_id for q in reloaded.question.questions] == ["q1", "q2"]+ public = public_pending_question(reloaded.question).to_dict()+ card = build_question_card(reloaded.question)+ assert len(public["questions"]) == len(card["questions"]) == 2+ serialized = json.dumps([public, card])+ assert "expected_answer" not in serialized and "PRIVATE" not in serialized+++ def test_independent_mixed_results_and_duplicate_credit(service):+ service.register_question("p", group())+ progress, interaction, replayed = service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "wrong"}+ )+ assert not replayed+ assert [r["is_correct"] for r in interaction.result["results"]] == [True, False]+ assert len(progress.quiz_attempts) == len(progress.learning_evidence) == 2+ assert {a.question_id for a in progress.quiz_attempts} == {"q1", "q2"}+ assert progress.mastery_levels["kp1"] > progress.mastery_levels["kp2"]+ assert progress.pending_question is None+ replay, _, replayed = service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "wrong"}+ )+ assert replayed and len(replay.quiz_attempts) == 2+++ @pytest.mark.parametrize(+ "answers",+ [{}, {"q1": "alpha", "q2": ""}, {"q1": "alpha", "q2": "beta", "other": "x"}],+ )+ def test_empty_or_unknown_answers_do_not_mutate(service, answers):+ service.register_question("p", group())+ before = service._store.load("p").model_dump()+ with pytest.raises(MasteryInteractionError):+ service.grade_interaction("p", answer="", question_id="g", answers=answers)+ assert service._store.load("p").model_dump() == before+++ def test_partial_answers_are_retained_and_graded_once_after_reload(service):+ service.register_question("p", group())+ recorded = service.record_question_answer(+ "p", "second only", interaction_id="g", answers={"q2": "beta"}+ )+ assert recorded.status == InteractionStatus.AWAITING_INPUT+ assert recorded.answers == {"q2": "beta"}+ reloaded = LearningService(LearningStore(service._store._root))+ progress, partial, replayed = reloaded.grade_interaction("p", answer="", question_id="g")+ assert not replayed+ assert partial.status == InteractionStatus.AWAITING_INPUT+ assert partial.result["complete"] is False+ assert partial.result["remaining_question_ids"] == ["q1"]+ assert partial.result["is_correct"] is None+ assert [result["question_id"] for result in partial.result["results"]] == ["q2"]+ assert [attempt.question_id for attempt in progress.quiz_attempts] == ["q2"]+ assert progress.pending_question.question_id == "g"+ replay, _, replayed = reloaded.grade_interaction(+ "p", answer="", question_id="g", answers={"q2": "beta"}+ )+ assert replayed and len(replay.quiz_attempts) == 1+ final, completed, replayed = reloaded.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha"}+ )+ assert not replayed+ assert completed.status == InteractionStatus.GRADED+ assert completed.answers == {"q1": "alpha", "q2": "beta"}+ assert completed.result["complete"] is True+ assert completed.result["remaining_question_ids"] == []+ assert [r["question_id"] for r in completed.result["results"]] == ["q1", "q2"]+ assert len(final.quiz_attempts) == len(final.learning_evidence) == 2+ assert final.pending_question is None+++ def test_changed_partial_reply_rolls_back_without_affecting_siblings(service):+ service.register_question("p", group())+ service.grade_interaction("p", answer="", question_id="g", answers={"q2": "wrong"})+ before = service._store.load("p").model_dump()+ with pytest.raises(MasteryInteractionError, match="committed answer"):+ service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "beta"}+ )+ assert service._store.load("p").model_dump() == before+++ def test_partial_leaf_repair_updates_parent_without_inventing_sibling_reply(service):+ service.register_question("p", group())+ service.grade_interaction("p", answer="", question_id="g", answers={"q2": "wrong"})+ service.repair_question(+ "p", "q2", action="correct", expected_answer="wrong", reason="Verified key correction"+ )+ parent = service._store.get_interaction("p", "g")+ assert parent.result["results"][0]["is_correct"] is True+ assert parent.result["results"][0].get("result") != "incorrect"+ assert parent.result["complete"] is False+ assert parent.question.questions[0].question_id == "q1"+ assert parent.question.questions[1].expected_answer == "wrong"+ assert parent.answers == {"q2": "wrong"}+ assert service._store.load("p").pending_question.questions[1].expected_answer == "wrong"+ service.repair_question("p", "q2", action="void", reason="Uncertain key")+ assert service._store.get_interaction("p", "g").result["results"][0]["is_correct"] is None+ assert service._store.load("p").pending_question.question_id == "g"+++ def test_third_answer_first_does_not_score_unanswered_questions(service):+ progress = service._store.load("p")+ progress.modules[0].knowledge_points.append(+ KnowledgePoint(id="kp3", name="third", type=KnowledgeType.MEMORY, module_id="m")+ )+ service.save(progress)+ pending = group()+ pending.questions.append(leaf("q3", "kp3", "gamma"))+ service.register_question("p", pending)+ progress, interaction, _ = service.grade_interaction(+ "p", answer="", question_id="g", answers={"q3": "gamma"}+ )+ assert [attempt.question_id for attempt in progress.quiz_attempts] == ["q3"]+ assert interaction.result["remaining_question_ids"] == ["q1", "q2"]+ assert interaction.status == InteractionStatus.AWAITING_INPUT+++ def test_partial_group_cannot_reuse_a_leaf_from_another_group(service):+ service.register_question("p", group())+ service.grade_interaction("p", answer="", question_id="g", answers={"q2": "beta"})+ replacement = group()+ replacement.question_id = "new-group"- service.register_question(- "p", replacement, pending_action="replace", replace_question_id="g"- )++ service.register_question("p", replacement, pending_action="replace", replace_question_id="g")+ before = service._store.load("p").model_dump()+ with pytest.raises(MasteryInteractionError, match="another interaction"):- service.grade_interaction(- "p", answer="", question_id="new-group", answers={"q2": "beta"}- )++ service.grade_interaction("p", answer="", question_id="new-group", answers={"q2": "beta"})+ assert service._store.load("p").model_dump() == before++--+ @pytest.mark.asyncio+ async def test_partial_grade_tool_and_status_preserve_child_identity(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: service)+ synced = []++ async def sync(**kwargs):+ synced.append(kwargs["pending"].question_id)++ monkeypatch.setattr(tools, "_sync_mastery_attempt_to_question_bank", sync)+ service.register_question("p", group())+ graded = await tools.MasteryGradeTool().execute(+ _mastery_path_id="p", question_id="g", answers={"q2": "beta"}+ )+ assert graded.success+ assert graded.metadata["mastery_grade"]["complete"] is False+ assert graded.metadata["mastery_grade"]["remaining_question_ids"] == ["q1"]+ assert synced == ["q2"]+ status = await tools.MasteryStatusTool().execute(_mastery_path_id="p")+ pending = status.metadata["mastery_status"]["pending_interaction"]+ assert pending["answers"] == {"q2": "beta"}+ assert pending["remaining_question_ids"] == ["q1"]+ assert "PRIVATE" not in json.dumps(pending)+++ def test_explicit_replacement_retains_abandoned_history(service):+ service.register_question("p", leaf("old"))+ with pytest.raises(MasteryInteractionError):+ service.register_question("p", group())+ _, _, created = service.register_question(+ "p", group(), pending_action="replace", replace_question_id="old"+ )+ assert created+ assert service._store.get_interaction("p", "old").status == InteractionStatus.ABANDONED+ assert not service._store.load("p").quiz_attempts+++ def test_invalid_group_leaf_objective_rolls_back_replacement(service):+ service.register_question("p", leaf("old"))+ bad = group()+ bad.questions[1].knowledge_point_id = "unknown"+ with pytest.raises(MasteryInteractionError):+ service.register_question("p", bad, pending_action="replace", replace_question_id="old")+ assert service._store.get_active_interaction("p").interaction_id == "old"+++ @pytest.mark.parametrize(+ "questions", [[leaf()], [leaf(), leaf()], [leaf(str(i)) for i in range(5)]]+ )+ def test_invalid_group_shape_rejected(questions):+ with pytest.raises(ValidationError):+ PendingQuestion(+ question_id="g", knowledge_point_id="kp1", question_type="group", questions=questions+ )+++ def test_native_single_compatibility(service):+ service.register_question("p", leaf())+ _, active, created = service.register_question("p", leaf("new"))+ assert not created and active.interaction_id == "q1"+ progress, interaction, _ = service.grade_interaction("p", answer="alpha", question_id="q1")+ assert interaction.result["is_correct"] is True+ assert len(progress.quiz_attempts) == 1+++ def test_group_rejects_duplicated_question_for_same_objective():+ with pytest.raises(ValidationError, match="distinct questions"):+ PendingQuestion(+ question_id="g",+ knowledge_point_id="kp1",+ question_type="group",+ questions=[leaf(), leaf("different-id")],+ )+++ @pytest.mark.asyncio+ async def test_quiz_tool_group_and_grade_tool_use_independent_contract(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: service)+ synced = []++ async def sync(**kwargs):+ synced.append(kwargs["pending"].question_id)++ monkeypatch.setattr(tools, "_sync_mastery_attempt_to_question_bank", sync)+ result = await tools.MasteryQuizTool().execute(+ _mastery_path_id="p",+ questions=[+ {"knowledge_point_id": "kp1", "question": "First?", "expected_answer": "alpha"},+ {"knowledge_point_id": "kp2", "question": "Second?", "expected_answer": "beta"},+ ],+ )+ assert result.success+ card = result.metadata["mastery_question"]+ assert len(card["questions"]) == 2+ leaves = service._store.get_active_interaction("p").question.questions+ graded = await tools.MasteryGradeTool().execute(+ _mastery_path_id="p",+ question_id=card["question_id"],+ answers={q.question_id: q.expected_answer for q in leaves},+ )+ assert graded.success+ payload = graded.metadata["mastery_grade"]+ assert len(payload["result"]["results"]) == 2+ assert set(synced) == {q.question_id for q in leaves}+++ @pytest.mark.asyncio+ async def test_replacement_requires_literal_current_learner_request(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: service)+ service.register_question("p", leaf("old"))+ kwargs = dict(+ _mastery_path_id="p",+ pending_action="replace",+ replace_question_id="old",+ replacement_request="Replace my question",+ _learner_message="Please explain",+ questions=[+ {"knowledge_point_id": "kp1", "question": "First?", "expected_answer": "alpha"},+ {"knowledge_point_id": "kp2", "question": "Second?", "expected_answer": "beta"},+ ],+ )+ result = await tools.MasteryQuizTool().execute(**kwargs)+ assert not result.success+ assert service._store.get_active_interaction("p").interaction_id == "old"+ kwargs["_learner_message"] = "Replace my question with two questions please"+ assert (await tools.MasteryQuizTool().execute(**kwargs)).success+++ def test_committed_group_answers_are_authoritative_after_reload(service):+ service.register_question("p", group())+ service.record_question_answer(+ "p", "display only", interaction_id="g", answers={"q1": "alpha", "q2": "wrong"}+ )+ reloaded = LearningService(LearningStore(service._store._root))+ stored = reloaded._store.get_active_interaction("p")+ assert stored.answers == {"q1": "alpha", "q2": "wrong"}+ with pytest.raises(MasteryInteractionError):+ reloaded.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "beta"}+ )+ _, interaction, _ = reloaded.grade_interaction("p", answer="", question_id="g")+ assert [r["is_correct"] for r in interaction.result["results"]] == [True, False]+++ def test_leaf_history_repair_does_not_change_sibling_credit(service):+ service.register_question("p", group())+ service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "wrong"}+ )+ assert service._store.get_interaction("p", "q2").question.expected_answer == "beta"+ progress, _ = service.repair_question(+ "p", "q2", action="correct", expected_answer="wrong", reason="Verified key correction"+ )+ assert len(progress.quiz_attempts) == 2+ assert all(attempt.is_correct for attempt in progress.quiz_attempts)+ assert all(r["is_correct"] for r in service._store.get_interaction("p", "g").result["results"])+ assert service._store.get_interaction("p", "g").question.questions[1].expected_answer == "wrong"+ progress, _ = service.repair_question("p", "q2", action="void", reason="Uncertain key")+ assert progress.quiz_attempts[0].is_correct and not progress.quiz_attempts[0].voided+ assert progress.quiz_attempts[1].voided+ parent = service._store.get_interaction("p", "g")+ assert parent.result["results"][1]["is_correct"] is None+ assert parent.result["is_correct"] is None+++ def test_parent_repair_cannot_grant_aggregate_credit(service):+ service.register_question("p", group())+ with pytest.raises(MasteryInteractionError):+ service.repair_question(+ "p",+ "g",+ action="correct",+ expected_answer="anything",+ reason="Cannot apply aggregate key",+ )+ assert not service._store.load("p").quiz_attempts+++ def test_removing_second_objective_abandons_whole_group(service):+ service.register_question("p", group())+ progress = service._store.load("p")+ progress.modules[0].knowledge_points = progress.modules[0].knowledge_points[:1]+ service.replace_modules_for_path("p", progress.modules)+ assert service._store.load("p").pending_question is None+ assert service._store.get_interaction("p", "g").status == InteractionStatus.ABANDONED+++ def test_unrelated_outline_change_keeps_pending_group_snapshot(service):+ service.register_question("p", group())+ before = service._store.get_active_interaction("p").model_dump()+ progress = service._store.load("p")+ progress.modules[0].name = "Updated section title"+ service.replace_modules_for_path("p", progress.modules)+ assert service._store.get_active_interaction("p").model_dump() == before+++ def test_defer_second_objective_retires_group_without_mastery_credit(service):+ service.register_question("p", group())+ progress, _ = service.defer_objective("p", "kp2", note="Return later")+ assert progress.pending_question is None and not progress.quiz_attempts+ assert service._store.get_interaction("p", "g").status == InteractionStatus.ABANDONED+++ def test_different_group_cannot_silently_reuse_existing(service):+ service.register_question("p", group())+ different = group()+ different.questions[1].prompt = "An unrelated question?"+ with pytest.raises(MasteryInteractionError):+ service.register_question("p", different)+++ def test_stale_replace_id_and_stale_submission_cannot_change_new_pending(service):+ service.register_question("p", leaf("old"))+ with pytest.raises(MasteryInteractionError):+ service.register_question(+ "p", group(), pending_action="replace", replace_question_id="stale"+ )+ service.register_question("p", group(), pending_action="replace", replace_question_id="old")+ with pytest.raises(MasteryInteractionError):+ service.grade_interaction("p", answer="alpha", question_id="old")+ assert service._store.get_active_interaction("p").interaction_id == "g"+++ def test_unreadable_choice_does_not_mark_any_group_answer_wrong(service):+ pending = group()+ pending.questions[1] = PendingQuestion(+ question_id="q2",+ knowledge_point_id="kp2",+ prompt="Choose?",+ question_type="choice",+ expected_answer="A",+ options=[{"label": "A", "body": "right"}, {"label": "B", "body": "wrong"}],+ )+ service.register_question("p", pending)+ with pytest.raises(MasteryInteractionError):+ service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "A or B"}+ )+ assert not service._store.load("p").quiz_attempts+++ def test_uncertain_visual_leaf_remains_ungraded_without_key_leak(service, monkeypatch):+ from deeptutor.learning import visual_practice++ pending = group()+ pending.questions[1].visual_context = {"task": "identification"}+ monkeypatch.setattr(+ visual_practice, "account_for_recent_assistance", lambda context, *_: context+ )+ monkeypatch.setattr(+ visual_practice, "evaluate_visual", lambda *_: ("ungraded", "Verify original image")+ )+ service.register_question("p", pending)+ progress, interaction, _ = service.grade_interaction(+ "p", answer="", question_id="g", answers={"q1": "alpha", "q2": "beta"}+ )+ assert len(progress.quiz_attempts) == 1+ result = interaction.result["results"][1]+ assert result["is_correct"] is None and result["result"] == "ungraded"+ assert result["correct_label"] == "" and "PRIVATE" not in json.dumps(result)+ assert interaction.result["is_correct"] is None+++ def test_group_definition_keeps_nested_answer_keys_sensitive():+ from deeptutor.capabilities.mastery.tools import MasteryQuizTool++ definition = MasteryQuizTool().get_definition()+ group_param = next(p for p in definition.parameters if p.name == "questions")+ assert group_param.sensitive+ assert group_param.items["properties"]["expected_answer"]["type"] == "string"+++ @pytest.mark.asyncio+ async def test_grade_tool_cannot_redirect_stale_id_to_active_group(service, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: service)+ service.register_question("p", group())+ result = await tools.MasteryGradeTool().execute(+ _mastery_path_id="p", question_id="stale", answers={"q1": "alpha", "q2": "beta"}+ )+ assert not result.success+ assert not service._store.load("p").quiz_attempts+ assert service._store.get_active_interaction("p").interaction_id == "g"diff --cc tests/capabilities/test_mastery_reviewed_revision.pyindex 2d093bbca,000000000..dd6c3c98bmode 100644,000000..100644--- a/tests/capabilities/test_mastery_reviewed_revision.py+++ b/tests/capabilities/test_mastery_reviewed_revision.py@@@ -1,603 -1,0 +1,644 @@@+"""Reviewed outline edits: real SQLite isolation, atomicity, and exact payloads."""++from concurrent.futures import ThreadPoolExecutor+from copy import deepcopy+import json+import sqlite3+from types import SimpleNamespace++import pytest++from deeptutor.capabilities.mastery.tools import (+ MasteryReviseTool,+ _plan_module_revision,+ _revise_specs,+)+from deeptutor.learning.models import (+ KnowledgePoint,+ KnowledgeType,+ LearningModule,+ MasteryInteraction,+ PendingQuestion,+ TopicMetadata,+ TopicSource,+ TopicSourceKind,+)+from deeptutor.learning.outline_revision import exact_diff+from deeptutor.learning.service import LearningService+from deeptutor.learning.storage import LearningConflictError, LearningStore+++def system(tmp_path):+ store = LearningStore(root=tmp_path)+ service = LearningService(store)+ modules = [+ LearningModule(+ id=f"m{i}",+ name=f"Module {i}",+ order=i,+ objective=f"Purpose {i}",+ knowledge_points=[+ KnowledgePoint(+ id=f"p{i}",+ name=f"Objective {i}",+ type=KnowledgeType.CONCEPT,+ module_id=f"m{i}",+ prerequisite_ids=["p0"] if i == 1 else [],+ required_visual_tasks=["relationship"] if i == 0 else [],+ )+ ],+ )+ for i in range(3)+ ]+ service.replace_modules_for_path("path", modules)++ def prepare(tx):+ tx.put_topic(+ TopicMetadata(path_id="path"),+ [+ TopicSource(+ id="source",+ kind=TopicSourceKind.BOOK,+ label="Synthetic source",+ )+ ],+ )+ tx.progress.modules[0].knowledge_points[0].topic_source_ids = ["source"]+ tx.progress.mastery_levels = {"p0": 0.3, "p2": 1.0}+ tx.progress.qualitative_mastery = {"p2": True}+ tx.progress.feynman_explanations = {"p2": "The comparison finally helped."}+ pending = PendingQuestion(+ question_id="question",+ knowledge_point_id="p0",+ module_id="m0",+ prompt="Explain the relationship",+ expected_answer="Because of the boundary",+ )+ tx.progress.pending_question = pending+ tx.put_interaction(+ MasteryInteraction(+ interaction_id="question",+ path_id="path",+ question=pending,+ session_id="session",+ )+ )++ store.mutate("path", prepare)+ return store, service+++def revisions():+ return [+ {+ "module_id": f"m{i}",+ "rewrite": [+ {+ "knowledge_point_id": f"p{i}",+ "name": f"Revised objective {i}",+ }+ ],+ }+ for i in range(2)+ ]+++def plan_revisions(progress, edits):+ specs, error = _revise_specs({"modules": edits})+ if error:+ raise ValueError(error)+ return _plan_module_revision(progress, specs)[0]+++def preview(system, edits=None):+ store, service = system+ progress = store.load("path")+ return service.preview_module_revision(+ "path",+ plan_revisions(progress, edits or revisions()),+ expected_revision=progress.version,+ session_id="session",+ )+++def state(progress):+ return progress.model_dump(mode="json", exclude={"version", "updated_at"})+++def apply_diff(before, changes):+ result = deepcopy(before)+ for change in changes:+ parts = [x.replace("~1", "/").replace("~0", "~") for x in change["path"].split("/")[1:]]+ target = result+ for part in parts[:-1]:+ target = target[int(part)] if isinstance(target, list) else target[part]+ key = int(parts[-1]) if isinstance(target, list) else parts[-1]+ if change["before_exists"]:+ assert target[key] == change["before"]+ if change["after_exists"]:+ target[key] = deepcopy(change["after"])+ else:+ del target[key]+ return result+++def test_preview_is_pure_and_commit_is_exact_and_retry_safe(system):+ store, service = system+ before = store.load("path")+ interaction = store.get_active_interaction("path").model_dump(mode="json")+ result, proposed = preview(system)+ assert result["module_order_changed"] is False+ assert result["before_module_order"] == result["proposed_module_order"]+ assert store.load("path").model_dump() == before.model_dump()+ assert store.get_active_interaction("path").model_dump(mode="json") == interaction+ assert apply_diff(state(before), result["changes"]) == state(proposed)+ assert proposed.modules[1].knowledge_points[0].prerequisite_ids == [+ proposed.modules[0].knowledge_points[0].id+ ]+ assert proposed.modules[0].knowledge_points[0].required_visual_tasks == ["relationship"]+ assert proposed.modules[0].knowledge_points[0].topic_source_ids == ["source"]+ assert proposed.mastery_levels["p2"] == 1+ assert proposed.feynman_explanations["p2"] == "The comparison finally helped."+ assert "p0" not in proposed.mastery_levels+ assert proposed.pending_question is None+ assert result["effects"]["active_interaction_removed"] is True+ committed, receipt = service.commit_module_revision(+ "path",+ result["preview_id"],+ session_id="session",+ )+ assert state(committed) == state(proposed)+ assert committed.version == before.version + 1+ assert not receipt["replayed"]+ assert store.get_active_interaction("path") is None+ # A fresh service (including a process restart) can safely retry the receipt.+ retry, receipt2 = LearningService(LearningStore(root=store._root)).commit_module_revision(+ "path",+ result["preview_id"],+ session_id="session",+ )+ assert retry.model_dump() == committed.model_dump()+ assert receipt2["replayed"]+ assert receipt2["applied_revision"] == committed.version+++def test_noop_preview_does_not_reset_or_publish_progress(system):+ store, service = system+ before = store.load("path")+ with pytest.raises(ValueError, match="changes nothing"):+ service.preview_module_revision(+ "path", before.modules, expected_revision=before.version, session_id="session"+ )+ assert store.load("path").model_dump() == before.model_dump()+++def test_unrelated_question_and_mastered_evidence_survive_batch(system):+ store, service = system+ before = store.get_active_interaction("path").model_dump()+ result, proposed = preview(system, [{"module_id": "m1", "add": [{"name": "Extra objective"}]}])+ assert proposed.pending_question.knowledge_point_id == "p0"+ committed, _ = service.commit_module_revision(+ "path", result["preview_id"], session_id="session"+ )+ assert store.get_active_interaction("path").model_dump() == before+ assert committed.qualitative_mastery["p2"] is True+++def test_retry_after_later_progress_returns_current_state_not_old_snapshot(system):+ store, service = system+ result, _ = preview(system)+ service.commit_module_revision("path", result["preview_id"], session_id="session")+ now = store.load("path")+ current = service.replace_modules_for_path("path", now.modules, name="Later name")+ replay, receipt = service.commit_module_revision(+ "path", result["preview_id"], session_id="session"+ )+ assert receipt["replayed"] is True+ assert receipt["applied_revision"] < replay.version+ assert replay.model_dump() == current.model_dump()+++def test_stale_preview_and_preview_load_race_cannot_overwrite(system):+ store, service = system+ result, _ = preview(system)+ old = store.load("path")+ current = service.replace_modules_for_path("path", old.modules, name="Changed name")+ with pytest.raises(LearningConflictError):+ service.commit_module_revision("path", result["preview_id"], session_id="session")+ with pytest.raises(LearningConflictError):+ service.preview_module_revision(+ "path", old.modules, expected_revision=old.version, session_id="session"+ )+ assert store.load("path").model_dump() == current.model_dump()+++def test_preview_is_scoped_to_path_session_and_workspace(system, tmp_path):+ store, service = system+ result, _ = preview(system)+ modules = store.load("path").modules+ modules[0].knowledge_points[0].topic_source_ids = []+ service.replace_modules_for_path("other", modules)+ for path_id, session in [("other", "session"), ("path", "different")]:+ with pytest.raises(ValueError, match="unavailable"):+ service.commit_module_revision(path_id, result["preview_id"], session_id=session)+ isolated = LearningService(LearningStore(root=tmp_path / "other-workspace"))+ isolated.replace_modules_for_path("path", modules)+ with pytest.raises(ValueError, match="unavailable"):+ isolated.commit_module_revision("path", result["preview_id"], session_id="session")+++def test_expired_or_tampered_preview_cannot_commit(system):+ store, service = system+ result, _ = preview(system)+ before = store.load("path").model_dump()+ with sqlite3.connect(store.db_path) as db:+ db.execute("UPDATE mastery_events SET created_at=0 WHERE id=?", (result["preview_id"],))+ with pytest.raises(ValueError, match="expired"):+ service.commit_module_revision("path", result["preview_id"], session_id="session")+ result, _ = preview(system)+ with sqlite3.connect(store.db_path) as db:+ raw = db.execute(+ "SELECT payload_json FROM mastery_events WHERE id=?", (result["preview_id"],)+ ).fetchone()[0]+ payload = json.loads(raw)+ payload["after_digest"] = "incorrect"+ db.execute(+ "UPDATE mastery_events SET payload_json=? WHERE id=?",+ (json.dumps(payload), result["preview_id"]),+ )+ with pytest.raises(ValueError, match="matches"):+ service.commit_module_revision("path", result["preview_id"], session_id="session")+ assert store.load("path").model_dump() == before+ assert store.get_active_interaction("path") is not None # SQL side effects rolled back too.+++def test_concurrent_drafts_have_one_winner_not_a_partial_merge(system):+ store, _ = system+ first, _ = preview(system)+ second, _ = preview(system, [{"module_id": "m1", "add": [{"name": "New objective"}]}])++ def commit(preview_id):+ try:+ return LearningService(LearningStore(root=store._root)).commit_module_revision(+ "path",+ preview_id,+ session_id="session",+ )[1]+ except LearningConflictError:+ return "conflict"++ with ThreadPoolExecutor(max_workers=2) as executor:+ results = list(executor.map(commit, [first["preview_id"], second["preview_id"]]))+ assert results.count("conflict") == 1+ assert sum(isinstance(x, dict) for x in results) == 1+++ "edit",+ [+ [{"module_id": "m2", "rewrite": [{"knowledge_point_id": "p2", "name": "New content"}]}],+ [{"module_id": "m0", "remove": ["p0"], "add": [{"name": "New content"}]}],+ [{"module_id": "m0", "add": [{"name": "New content", "prerequisite_ids": ["unknown"]}]}],+ [+ {+ "module_id": "m0",+ "rewrite": [+ {"knowledge_point_id": "p0", "name": "New content", "prerequisite_ids": ["p1"]}+ ],+ }+ ],+ ],+)+def test_invalid_batch_is_all_or_nothing(system, edit):+ store, _ = system+ before = store.load("path").model_dump()+ with pytest.raises(ValueError):+ preview(system, edit)+ assert store.load("path").model_dump() == before+ assert store.get_active_interaction("path") is not None+++def test_exact_diff_preserves_types_null_removals_and_pointer_escaping():+ before = {"a/b~c": {"old": None, "keep": True}, "list": [1, 2]}+ after = {"a/b~c": {"new": None, "keep": 1}, "list": [1]}+ changes = exact_diff(before, after)+ assert any(c["path"] == "/a~1b~0c/keep" for c in changes)+ assert apply_diff(before, changes) == after+ assert exact_diff({"nested": [True]}, {"nested": [1]}) == [+ {+ "path": "/nested/0",+ "before_exists": True,+ "after_exists": True,+ "before": True,+ "after": 1,+ }+ ]+++async def test_reorder_only_preview_commit_preserves_every_objective_and_pending_question(+ system, monkeypatch+):+ from deeptutor.capabilities.mastery import tools++ store, service = system+ monkeypatch.setattr(tools, "_new_service", lambda: service)+ before = store.load("path")+ interaction = store.get_active_interaction("path").model_dump(mode="json")+ args = {+ "_mastery_path_id": "path",+ "_session_id": "session",+ "_mastery_session_mode": "outline",+ }+ tool = MasteryReviseTool()+ preview_result = await tool.execute(**args, action="preview", module_order=["m2", "m0", "m1"])+ assert preview_result.success, preview_result.content+ draft = json.loads(preview_result.content)+ assert draft["status"] == "preview_only_not_saved"+ assert draft["before_module_order"] == ["m0", "m1", "m2"]+ assert draft["proposed_module_order"] == ["m2", "m0", "m1"]+ assert draft["module_order_changed"] is True+ assert store.load("path").model_dump() == before.model_dump()+ result = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ assert result.success, result.content+ receipt = json.loads(result.content)+ assert receipt["applied_module_order"] == ["m2", "m0", "m1"]+ committed = store.load("path")+ assert [m.id for m in committed.modules] == ["m2", "m0", "m1"]+ assert [m.order for m in committed.modules] == [0, 1, 2]+ assert committed.current_module_id == before.current_module_id+ assert committed.current_kp_index == before.current_kp_index+ assert committed.pending_question == before.pending_question+ assert store.get_active_interaction("path").model_dump(mode="json") == interaction+ for field in (+ "mastery_levels",+ "qualitative_mastery",+ "feynman_explanations",+ "knowledge_types",+ ):+ assert getattr(committed, field) == getattr(before, field)+ original = {m.id: m for m in before.modules}+ for module in committed.modules:+ assert module.model_dump(exclude={"order"}) == original[module.id].model_dump(+ exclude={"order"}+ )+ assert apply_diff(state(before), draft["changes"]) == state(committed)+ replay = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ assert json.loads(replay.content)["replayed"] is True+ assert store.load("path").model_dump() == committed.model_dump()+++ "order",+ [+ [],+ ["m0", "m1"],+ ["m0", "m1", "m1"],+ ["m0", "m1", "foreign"],+ ["m0", "m1", 2],+ "m2,m0,m1",+ ],+)+async def test_invalid_order_refuses_whole_preview_even_with_valid_content_edit(+ system, monkeypatch, order+):+ from deeptutor.capabilities.mastery import tools++ store, service = system+ monkeypatch.setattr(tools, "_new_service", lambda: service)+ before = store.load("path").model_dump()+ result = await MasteryReviseTool().execute(+ _mastery_path_id="path",+ _session_id="session",+ _mastery_session_mode="outline",+ action="preview",+ modules=revisions(),+ module_order=order,+ )+ assert not result.success+ assert store.load("path").model_dump() == before+ with sqlite3.connect(store.db_path) as db:+ count = db.execute(+ "SELECT COUNT(*) FROM mastery_events WHERE event_type='path.modules_previewed'"+ ).fetchone()[0]+ assert count == 0+++async def test_order_requires_review_and_combined_edit_has_exact_diff(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ store, service = system+ monkeypatch.setattr(tools, "_new_service", lambda: service)+ tool = MasteryReviseTool()+ args = {+ "_mastery_path_id": "path",+ "_session_id": "session",+ "_mastery_session_mode": "outline",+ }+ before = store.load("path")+ refused = await tool.execute(**args, module_order=["m2", "m0", "m1"], modules=revisions())+ assert not refused.success+ result = await tool.execute(+ **args, action="preview", module_order=["m2", "m0", "m1"], modules=revisions()+ )+ assert result.success, result.content+ draft = json.loads(result.content)+ assert store.load("path").model_dump() == before.model_dump()+ committed = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ assert committed.success, committed.content+ after = store.load("path")+ assert apply_diff(state(before), draft["changes"]) == state(after)+ assert after.modules[1].knowledge_points[0].name == "Revised objective 0"+ assert after.mastery_levels["p2"] == 1+++async def test_reorder_noop_stale_preview_and_historical_commit_receipt(system, monkeypatch):+ import jsonschema++ from deeptutor.capabilities.mastery import tools++ store, service = system+ monkeypatch.setattr(tools, "_new_service", lambda: service)+ tool = MasteryReviseTool()+ args = {+ "_mastery_path_id": "path",+ "_session_id": "session",+ "_mastery_session_mode": "outline",+ }+ schema = tool.get_definition().to_openai_schema()["function"]["parameters"]+ request = {"action": "preview", "module_order": ["m2", "m0", "m1"]}+ jsonschema.validate(request, schema)+ before = store.load("path")+ noop = await tool.execute(**args, action="preview", module_order=["m0", "m1", "m2"])+ assert not noop.success and "changes nothing" in noop.content+ assert store.load("path").model_dump() == before.model_dump()+ draft = json.loads((await tool.execute(**args, **request)).content)+ service.replace_modules_for_path("path", before.modules)+ stale = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ assert not stale.success+ assert [m.id for m in store.load("path").modules] == ["m0", "m1", "m2"]+ draft = json.loads((await tool.execute(**args, **request)).content)+ committed = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ assert committed.success+ later_modules = _plan_module_revision(store.load("path"), {}, module_order=["m1", "m2", "m0"])[+ 0+ ]+ service.replace_modules_for_path("path", later_modules)+ replay_result = await tool.execute(**args, action="commit", preview_id=draft["preview_id"])+ replay = json.loads(replay_result.content)+ assert replay["replayed"] is True+ assert replay["applied_module_order"] == ["m2", "m0", "m1"]+ assert replay["current_module_order"] == ["m1", "m2", "m0"]+++async def test_runtime_preview_requires_a_later_invocation_and_preserves_legacy_schema(+ system, monkeypatch+):+ import jsonschema++ from deeptutor.agents.loop.agent_loop import AgentLoop+ from deeptutor.capabilities.mastery import tools+ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.capabilities.mastery.pipeline import MasteryLoopPipeline+ from deeptutor.core.context import UnifiedContext+ from deeptutor.runtime.stream_bus import StreamBus++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ context = UnifiedContext(+ session_id="session",+ metadata={+ "mastery_mode": True,+ "mastery_path_id": "path",+ "mastery_session_mode": "outline",+ },+ )+ pipeline = MasteryLoopPipeline(language="en")++ async def chunks():+ yield SimpleNamespace(+ choices=[+ SimpleNamespace(+ delta=SimpleNamespace(content="Reviewed.", tool_calls=None),+ finish_reason="stop",+ )+ ],+ usage=None,+ )++ async def create(**kwargs):+ return chunks()++ engine = AgentLoop(+ pipeline=pipeline,+ context=context,+ stream=StreamBus(),+ client=SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create))),+ enabled_tools=[],+ tool_schemas=None,+ )++ async def invoke():+ await engine._call_llm(+ messages=[{"role": "user", "content": "Review the outline."}],+ label="review",+ call_kind="agent_loop_round",+ trace_role="answer",+ max_tokens=100,+ )++ capability = MasteryLoopCapability()+ tool = MasteryReviseTool()+ schema = tool.get_definition().to_openai_schema()["function"]["parameters"]+ edits = {"action": "preview", "modules": revisions()}+ jsonschema.validate(edits, schema)+ await invoke()+ args = capability.augment_kwargs(+ tool.name,+ {**edits, "_revision_request_id": "untrusted-model-value"},+ context,+ )+ invocation = args["_revision_request_id"]+ assert invocation and invocation != "untrusted-model-value"+ result = await tool.execute(**args)+ assert result.success, result.content+ assert "mastery_revision_preview" in result.metadata+ assert "mastery_revise" not in result.metadata+ commit = {"action": "commit", "preview_id": json.loads(result.content)["preview_id"]}+ jsonschema.validate(commit, schema)+ blocked = await tool.execute(**capability.augment_kwargs(tool.name, commit, context))+ assert not blocked.success and "later model round" in blocked.content+ await invoke()+ args = capability.augment_kwargs(tool.name, commit, context)+ assert args["_revision_request_id"] != invocation+ result = await tool.execute(**args)+ assert result.success, result.content+ # Existing callers omit action and still have their original schema.+ jsonschema.validate({"modules": revisions()}, schema)+++async def test_reviewed_tool_scope_and_commit_cannot_replace_reviewed_payload(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ tool = MasteryReviseTool()+ bound = {"_mastery_path_id": "path", "_session_id": "session"}+ result = await tool.execute(+ action="preview", modules=revisions(), **bound, _mastery_session_mode="study"+ )+ assert not result.success+ result = await tool.execute(+ action="preview", modules=revisions(), **bound, _mastery_session_mode="outline"+ )+ assert result.success, result.content+ preview_id = json.loads(result.content)["preview_id"]+ result = await tool.execute(+ action="commit", preview_id=preview_id, modules=revisions(), **bound+ )+ assert not result.success and "only preview_id" in result.content++++++def test_group_child_revision_is_previewed_without_retiring_live_questions(system):++ store, service = system++++ def group_questions(tx):++ first = tx.progress.pending_question.model_copy(deep=True)++ first.question_id = "child-0"++ second = first.model_copy(++ update={"question_id": "child-1", "knowledge_point_id": "p1", "module_id": "m1"}++ )++ group = first.model_copy(++ update={++ "question_id": "question",++ "question_type": "group",++ "expected_answer": "",++ "questions": [first, second],++ }++ )++ tx.progress.pending_question = group++ active = tx.active_interaction()++ active.question = group++ tx.put_interaction(active)++++ store.mutate("path", group_questions)++ before = store.get_active_interaction("path").model_dump()++ result, proposed = preview(++ system,++ [++ {++ "module_id": "m1",++ "rewrite": [{"knowledge_point_id": "p1", "name": "Changed child objective"}],++ }++ ],++ )++ assert proposed.pending_question is None++ assert result["effects"]["active_interaction_removed"] is True++ assert store.get_active_interaction("path").model_dump() == before++ service.commit_module_revision("path", result["preview_id"], session_id="session")++ assert store.get_active_interaction("path") is None++ assert store.load("path").pending_question is Nonediff --cc tests/services/session/test_mastery_group_runtime.pyindex 000000000,1fa783907..b952922a2mode 000000,100644..100644--- a/tests/services/session/test_mastery_group_runtime.py+++ b/tests/services/session/test_mastery_group_runtime.py@@@ -1,0 -1,203 +1,204 @@@+ """Group answers stay independently identified across the runtime boundary."""++ from types import SimpleNamespace++ from pydantic import ValidationError+ import pytest++ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.core.context import UnifiedContext+ from deeptutor.core.turn_request import MasteryCardAnswer+ from deeptutor.services.session.turns.learning_adapter import LearningTurnAdapter+++ def test_card_contract_keeps_independent_group_answers():+ card = MasteryCardAnswer(+ question_id="group", text="1: A; 2: B", answers={"first": "A", "second": "B"}+ )+ assert card.model_dump()["answers"] == {"first": "A", "second": "B"}+ assert MasteryCardAnswer(question_id="single", text="A").answers is None++- "answers", [{}, {"first": "", "second": "B"}, {"first": 1, "second": "B"}]-)[email protected]("answers", [{}, {"first": "", "second": "B"}, {"first": 1, "second": "B"}])+ def test_group_transport_rejects_empty_or_untyped_values(answers):+ with pytest.raises(ValidationError):+ MasteryCardAnswer(question_id="group", text="display", answers=answers)+++ def test_group_transport_accepts_one_actual_reply():+ card = MasteryCardAnswer(question_id="group", text="second only", answers={"second": "B"})+ assert card.answers == {"second": "B"}+++ def test_partial_group_seed_does_not_claim_unanswered_questions_were_graded():- context = UnifiedContext(metadata={- "mastery_mode": True,- "mastery_card_grade": {- "result": {- "question_type": "group", "complete": False,- "remaining_question_ids": ["first"],- "results": [{"question_id": "second", "is_correct": True}],++ context = UnifiedContext(++ metadata={++ "mastery_mode": True,++ "mastery_card_grade": {++ "result": {++ "question_type": "group",++ "complete": False,++ "remaining_question_ids": ["first"],++ "results": [{"question_id": "second", "is_correct": True}],++ },+ },- },- })++ }++ )+ seed = MasteryLoopCapability().pre_loop_seed(context)+ assert "first" in seed and "unanswered" in seed+ assert "second: correct" in seed+ assert "The question group was already graded" not in seed+++ @pytest.mark.asyncio+ async def test_runtime_forwards_group_map_not_display_summary(monkeypatch):+ calls = []+ published = []++ async def grade(self, **kwargs):+ calls.append(kwargs)+ return SimpleNamespace(+ success=True,+ content="{}",+ metadata={+ "mastery_grade": {+ "question_id": "group",+ "result": {"results": []},+ "is_correct": False,+ }+ },+ )++ async def publish(execution, event):+ published.append(event)+ return {}++ monkeypatch.setattr("deeptutor.capabilities.mastery.tools.MasteryGradeTool.execute", grade)+ adapter = LearningTurnAdapter()+ adapter._publish_live_event = publish+ result = await adapter._grade_submitted_card_answer(+ SimpleNamespace(session_id="session", turn_id="turn"),+ path_id="path",+ answer={+ "question_id": "group",+ "text": "display only",+ "answers": {"first": "A", "second": "B"},+ },+ )+ assert result["question_id"] == "group"+ assert calls[0]["answers"] == {"first": "A", "second": "B"}+ assert calls[0].get("answer", "") != "display only"+ assert len(published) == 2+++ @pytest.mark.asyncio+ async def test_commit_keeps_group_map_in_the_native_answer_record(monkeypatch):+ calls = []++ def record(self, path_id, answer, **kwargs):+ calls.append((path_id, answer, kwargs))++ monkeypatch.setattr("deeptutor.learning.service.LearningService.record_question_answer", record)+ await LearningTurnAdapter()._commit_mastery_card_answer(+ path_id="path",+ session_id="session",+ turn_id="turn",+ question_id="group",+ answer="display only",+ answers={"first": "A", "second": "B"},+ )+ assert calls[0][2]["answers"] == {"first": "A", "second": "B"}+++ @pytest.mark.parametrize(+ "reply",+ [+ "Answer these two practice questions; I will grade both answers.\n1. Which change increases the rate?\n2. Explain why it increases?",+ "Válaszolj erre a két gyakorló kérdésre.\n1. Melyik változás növeli a sebességet?\n2. Miért növeli?",+ ],+ )+ def test_explicit_numbered_assessment_cannot_finish_as_unregistered_prose(reply):+ instruction = MasteryLoopCapability().finish_instruction(+ UnifiedContext(metadata={"mastery_mode": True}), reply+ )+ assert instruction is not None+ assert "mastery_quiz" in instruction+++ @pytest.mark.parametrize(+ "reply",+ [+ "Two useful ideas:\n1. Motion is random.\n2. The gradient changes net motion.",+ "Think about two examples:\n1. Where does it move?\n2. Which force matters?",+ "A korábbi kérdésről beszélünk, nem új feladatról.\n1. Miért fontos az irány?\n2. Mire utal a különbség?",+ ],+ )+ def test_connected_teaching_is_not_a_forced_assessment(reply):+ assert (+ MasteryLoopCapability().finish_instruction(+ UnifiedContext(metadata={"mastery_mode": True}), reply+ )+ is None+ )+++ def test_group_seed_reads_real_nested_results_and_keeps_unknown_neutral():+ context = UnifiedContext(+ metadata={+ "mastery_mode": True,+ "mastery_card_grade": {+ "question_id": "group",+ "is_correct": None,+ "result": {+ "question_type": "group",+ "results": [+ {+ "question_id": "first",+ "knowledge_point_id": "point-a",+ "is_correct": True,+ },+ {+ "question_id": "second",+ "knowledge_point_id": "point-b",+ "is_correct": None,+ },+ ],+ },+ },+ }+ )+ seed = MasteryLoopCapability().pre_loop_seed(context)+ assert "first: correct" in seed+ assert "second: ungraded" in seed+ assert "second: incorrect" not in seed+++ @pytest.mark.asyncio+ async def test_rejected_group_answer_emits_card_recovery_event(monkeypatch):+ published = []++ async def grade(self, **kwargs):+ return SimpleNamespace(success=False, content="invalid answers", metadata={})++ async def publish(execution, event):+ published.append(event)+ return {}++ monkeypatch.setattr("deeptutor.capabilities.mastery.tools.MasteryGradeTool.execute", grade)+ adapter = LearningTurnAdapter()+ adapter._publish_live_event = publish+ result = await adapter._grade_submitted_card_answer(+ SimpleNamespace(session_id="session", turn_id="turn"),+ path_id="path",+ answer={+ "question_id": "group",+ "text": "display",+ "answers": {"first": "A", "second": "B"},+ },+ )+ assert result is None+ assert len(published) == 2+ metadata = published[0].metadata+ assert metadata["tool_metadata"]["mastery_answer_rejected"]["question_id"] == "group"+ assert "turn" in metadata["call_id"]+ assert "mastery_grade" not in metadata["tool_metadata"]