DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): localize learner profile persistence notices
Bingxi Zhao (Frank)9ca096b45610
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex eebcaeabe..37bb7b569 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -284,8 +284,10 @@ class MasteryLoopCapability:state["profile_write_pending"] = Truedef profile_recorded(receipt):- if (state.get("profile_selection") == selection- and context.metadata.get("mastery_path_id") == path_id):+ if (+ state.get("profile_selection") == selection+ and context.metadata.get("mastery_path_id") == path_id+ ):state["profile_write_pending"] = Falsestate["profile_receipt"] = receipt@@ -437,10 +439,11 @@ class MasteryLoopCapability:# it does not classify or discard the learner-facing explanation.state["profile_write_pending"] = Falsestate["profile_receipt"] = {"status": "not_saved"}- notice = (- "Storage status: the requested learner-profile update was not saved for "- "future sessions. It can still guide this conversation."- )+ from deeptutor.services.prompt import get_prompt_manager+ from deeptutor.services.prompt.lookup import prompt_text++ pack = get_prompt_manager().load_prompts("mastery", "mastery_loop", context.language)+ notice = prompt_text(pack, ("notices", "profile_not_saved"))def with_notice(override):if not notice:diff --git a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yamlindex 1b936c6a7..0e8ca73bf 100644--- a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml@@ -133,3 +133,6 @@ playbook: |-**Changing mode is itself a teaching action.** When the learner asks for something this mode cannot do — a refused tool will name the mode it needs — call `mastery_mode`, and **say which mode you moved to and why**: the mode is shown above the conversation and they can press it themselves. Then finish the job in the same round; do not stop and make them repeat themselves. When the work is done and the mode you came from is what they are really doing, switch back.Keep each round focused on one objective.++notices:+ profile_not_saved: "Storage status: the requested learner-profile update was not saved for future sessions. It can still guide this conversation."diff --git a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yamlindex a9e6e1c67..629d6aeeb 100644--- a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml@@ -130,3 +130,6 @@ playbook: |-**模式是可以切换的,切换本身也是一次教学动作。** 学习者要的事情当前模式做不了时(工具会拒绝并告诉你该切到哪个模式),就调用 `mastery_mode` 切过去,并且**告诉他你切到了哪个模式、为什么**——顶部就显示着当前模式,他自己也能点。切完就在同一轮把事情做完,不要停下来等他再说一遍。事情做完之后,如果原来的模式才是他真正在做的事,就切回去。每一轮聚焦一个知识点。++notices:+ profile_not_saved: "保存状态:本次学习档案更新未能保存到后续会话,但仍可用于当前对话。"diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex 62c91af68..efea7f66c 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -2119,7 +2119,9 @@ class MasteryProfileTool(BaseTool):required=False,),ToolParameter(- name="teaching_updates", type="array", required=False,+ name="teaching_updates",+ type="array",+ required=False,description=("1-6 keyed upsert/remove operations. Preference requires an explicit ""learner_report with evidence. Observation requires a current path "@@ -2132,16 +2134,31 @@ class MasteryProfileTool(BaseTool):items=TeachingUpdate.model_json_schema(),),ToolParameter(- name="expected_revision", type="integer", required=False,+ name="expected_revision",+ type="integer",+ required=False,description="Required with teaching_updates or clear_fields: path_revision from the current mastery snapshot. Refresh after conflict.",),ToolParameter(- name="clear_fields", type="array", required=False,+ name="clear_fields",+ type="array",+ required=False,description="Explicitly forget only the intake fields the learner asked to remove. Blank values never clear a field.",- items={"type": "string", "enum": ["prior_knowledge", "target_level", "time_budget", "preferences", "notes"]},+ items={+ "type": "string",+ "enum": [+ "prior_knowledge",+ "target_level",+ "time_budget",+ "preferences",+ "notes",+ ],+ },),ToolParameter(- name="clear_request", type="string", required=False,+ name="clear_request",+ type="string",+ required=False,description="Literal quote from the current learner request authorizing clear_fields. Omit unless clearing.",),],@@ -2189,19 +2206,28 @@ class MasteryProfileTool(BaseTool):try:progress, changed = service.record_learner_profile(- path_id, fields=fields,- session_id=_resolve_session_id(kwargs), turn_id=_resolve_turn_id(kwargs),- teaching_updates=updates, expected_revision=kwargs.get("expected_revision"),+ path_id,+ fields=fields,+ session_id=_resolve_session_id(kwargs),+ turn_id=_resolve_turn_id(kwargs),+ teaching_updates=updates,+ expected_revision=kwargs.get("expected_revision"),learner_message=str(kwargs.get("_learner_message") or ""),- clear_fields=clear_fields, clear_request=kwargs.get("clear_request") or "",+ clear_fields=clear_fields,+ clear_request=kwargs.get("clear_request") or "",)except (ValueError, LearningStoreError) as exc:return ToolResult(content=str(exc), success=False)except KeyError:- return ToolResult(content="The bound mastery path no longer exists. Refresh the current path.", success=False)+ return ToolResult(+ content="The bound mastery path no longer exists. Refresh the current path.",+ success=False,+ )receipt = kwargs.get("_profile_recorded")if callable(receipt):- receipt({"path_id": path_id, "path_revision": progress.version, "updated_fields": changed})+ receipt(+ {"path_id": path_id, "path_revision": progress.version, "updated_fields": changed}+ )return _json_result({"status": "recorded",diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.pyindex 03e732752..c47467489 100644--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@ -1309,13 +1309,23 @@ class LearningService:# Deletion has its own explicit, quoted, revision-fenced operation.if clear_fields is not None and (not isinstance(clear_fields, list)- or any(not isinstance(key, str) or key not in _LEARNER_PROFILE_FIELDS- or key == "teaching_strategy" for key in clear_fields)+ or any(+ not isinstance(key, str)+ or key not in _LEARNER_PROFILE_FIELDS+ or key == "teaching_strategy"+ for key in clear_fields+ )):raise ValueError("clear_fields must name intake text fields")if clear_fields:- if not isinstance(clear_request, str) or not clear_request.strip() or clear_request not in learner_message:- raise ValueError("clear_request must be a literal quote from the current learner message")+ if (+ not isinstance(clear_request, str)+ or not clear_request.strip()+ or clear_request not in learner_message+ ):+ raise ValueError(+ "clear_request must be a literal quote from the current learner message"+ )if any(key in cleaned for key in clear_fields):raise ValueError("Cannot update and clear the same profile field")if type(expected_revision) is not int or expected_revision < 0:diff --git a/deeptutor/learning/teaching.py b/deeptutor/learning/teaching.pyindex e07c2105e..de451bf0d 100644--- a/deeptutor/learning/teaching.py+++ b/deeptutor/learning/teaching.py@@ -129,10 +129,14 @@ def teaching_guidance("teaching_focus": {"knowledge_point_id": knowledge_point_id,"observations": [- {"key": key, **item.model_dump(- exclude={"session_id", "turn_id", "updated_at", "knowledge_point_id"}- )}- for key, item in observations if item.knowledge_point_id == knowledge_point_id+ {+ "key": key,+ **item.model_dump(+ exclude={"session_id", "turn_id", "updated_at", "knowledge_point_id"}+ ),+ }+ for key, item in observations+ if item.knowledge_point_id == knowledge_point_id][:3],"instruction": ("Use the current learner request and these objective-local notes to choose the next "diff --git a/tests/capabilities/test_mastery_profile_continuity.py b/tests/capabilities/test_mastery_profile_continuity.pyindex 3b8a4cb11..aa9ed3835 100644--- a/tests/capabilities/test_mastery_profile_continuity.py+++ b/tests/capabilities/test_mastery_profile_continuity.py@@ -14,12 +14,31 @@ from deeptutor.learning.storage import LearningConflictError, LearningStoredef system(tmp_path, monkeypatch):store = LearningStore(root=tmp_path)service = LearningService(store)- service.replace_modules_for_path("path", [LearningModule(id="m", name="Basics", order=0,- knowledge_points=[KnowledgePoint(id="p", name="Boundary", module_id="m", type="concept")])])+ service.replace_modules_for_path(+ "path",+ [+ LearningModule(+ id="m",+ name="Basics",+ order=0,+ knowledge_points=[+ KnowledgePoint(id="p", name="Boundary", module_id="m", type="concept")+ ],+ )+ ],+ )monkeypatch.setattr("deeptutor.capabilities.mastery.tools._new_service", lambda: service)- service.record_learner_profile("path", fields={"prior_knowledge": "Basic algebra",- "target_level": "Explain independently", "time_budget": "Two weeks",- "preferences": "Use diagrams", "notes": "Evening study"}, session_id="first")+ service.record_learner_profile(+ "path",+ fields={+ "prior_knowledge": "Basic algebra",+ "target_level": "Explain independently",+ "time_budget": "Two weeks",+ "preferences": "Use diagrams",+ "notes": "Evening study",+ },+ session_id="first",+ )return store, service@@ -27,42 +46,72 @@ def system(tmp_path, monkeypatch):async def test_blank_optional_arguments_do_not_erase_intake_during_feedback(system, tmp_path):store, service = systembefore = store.load("path")- result = await MasteryProfileTool().execute(_mastery_path_id="path", _session_id="second",- prior_knowledge="", target_level=None, time_budget=" ", preferences="", notes="",+ result = await MasteryProfileTool().execute(+ _mastery_path_id="path",+ _session_id="second",+ prior_knowledge="",+ target_level=None,+ time_budget=" ",+ preferences="",+ notes="",expected_revision=before.version,- _learner_message="Use connected explanations.", teaching_updates=[{- "kind": "preference", "op": "upsert", "key": "pace",- "text": "Use connected explanations", "basis": "learner_report",- "evidence": "Use connected explanations.",- }])+ _learner_message="Use connected explanations.",+ teaching_updates=[+ {+ "kind": "preference",+ "op": "upsert",+ "key": "pace",+ "text": "Use connected explanations",+ "basis": "learner_report",+ "evidence": "Use connected explanations.",+ }+ ],+ )assert result.success, result.contentloaded = LearningStore(root=tmp_path).load("path")for name in ("prior_knowledge", "target_level", "time_budget", "preferences", "notes"):assert getattr(loaded.learner_profile, name) == getattr(before.learner_profile, name)assert json.loads(result.content)["updated_fields"] == ["teaching_preferences"]# Direct service callers receive the same partial-update semantics.- after, changed = service.record_learner_profile("path", fields={"notes": " ", "time_budget": None})+ after, changed = service.record_learner_profile(+ "path", fields={"notes": " ", "time_budget": None}+ )assert changed == [] and after.version == loaded.version@pytest.mark.asyncioasync def test_current_correction_survives_new_session_and_keeps_unrelated_preferences(system):store, service = system- service.record_learner_profile("path", fields={"preferences": "Connected explanations now"},- session_id="later", turn_id="correction")- status = json.loads((await MasteryStatusTool().execute(_mastery_path_id="path",- _session_id="fresh-session")).content)+ service.record_learner_profile(+ "path",+ fields={"preferences": "Connected explanations now"},+ session_id="later",+ turn_id="correction",+ )+ status = json.loads(+ (+ await MasteryStatusTool().execute(_mastery_path_id="path", _session_id="fresh-session")+ ).content+ )assert status["learner_profile"]["preferences"] == "Connected explanations now"assert status["learner_profile"]["time_budget"] == "Two weeks"- assert "fresh path preferences over conflicting historical summaries" in status["learner_profile"]["teaching_guidance"]+ assert (+ "fresh path preferences over conflicting historical summaries"+ in status["learner_profile"]["teaching_guidance"]+ )def test_clear_is_explicit_quoted_revision_fenced_and_idempotent(system):store, service = systemrevision = store.load("path").versionrequest = "Forget my old time budget."- kwargs = dict(fields={}, clear_fields=["time_budget"], clear_request=request,- learner_message=request, expected_revision=revision)+ kwargs = dict(+ fields={},+ clear_fields=["time_budget"],+ clear_request=request,+ learner_message=request,+ expected_revision=revision,+ )progress, changed = service.record_learner_profile("path", **kwargs)assert changed == ["time_budget"]assert progress.learner_profile.time_budget == ""@@ -81,13 +130,18 @@ async def test_selected_profile_write_needs_a_successful_native_receipt(system):from deeptutor.core.context import UnifiedContextcap = MasteryLoopCapability()- context = UnifiedContext(user_message="Use connected explanations.", session_id="new",- metadata={"mastery_mode": True, "mastery_path_id": "path"})+ context = UnifiedContext(+ user_message="Use connected explanations.",+ session_id="new",+ metadata={"mastery_mode": True, "mastery_path_id": "path"},+ )kwargs = cap.augment_kwargs("mastery_profile", {"teaching_strategy": "invalid"}, context)failure = await MasteryProfileTool().execute(**kwargs)assert not failure.successassert "mastery_profile" in cap.finish_instruction(context, "Saved for next time.")- corrected = cap.augment_kwargs("mastery_profile", {"preferences": "Connected explanations"}, context)+ corrected = cap.augment_kwargs(+ "mastery_profile", {"preferences": "Connected explanations"}, context+ )result = await MasteryProfileTool().execute(**corrected)assert result.successassert cap.finish_instruction(context, "Saved for next time.") is None@@ -100,27 +154,33 @@ async def test_profile_failure_has_one_repair_round_then_teaching_with_unsaved_nfrom deeptutor.core.context import UnifiedContextcap = MasteryLoopCapability()- context = UnifiedContext(user_message="Use connected explanations.",- metadata={"mastery_mode": True, "mastery_path_id": "path"})- result = await MasteryProfileTool().execute(**cap.augment_kwargs(- "mastery_profile", {"teaching_strategy": "invalid"}, context))+ context = UnifiedContext(+ user_message="Use connected explanations.",+ metadata={"mastery_mode": True, "mastery_path_id": "path"},+ )+ result = await MasteryProfileTool().execute(+ **cap.augment_kwargs("mastery_profile", {"teaching_strategy": "invalid"}, context)+ )assert not result.successassert cap.finish_instruction(context, "Saved for next time.") is not None- teaching = "A boundary separates the two regions. We can follow their relationship step by step."+ teaching = (+ "A boundary separates the two regions. We can follow their relationship step by step."+ )assert cap.finish_instruction(context, teaching) is Nonevisible = cap.final_text_override(context, teaching)assert "not saved" in visible and teaching in visibleassert context.extension("mastery")["profile_receipt"]["status"] == "not_saved"-def test_unsaved_notice_preserves_card_finish_postcondition():[email protected]("language, notice", [("en", "not saved"), ("zh", "未能保存")])+def test_unsaved_notice_preserves_card_finish_postcondition(language, notice):from deeptutor.capabilities.mastery.loop import MasteryLoopCapabilityfrom deeptutor.core.context import UnifiedContext- context = UnifiedContext(metadata={"mastery_mode": True})+ context = UnifiedContext(language=language, metadata={"mastery_mode": True})context.extension("mastery").update(profile_write_pending=True, card_posted=True)visible = MasteryLoopCapability().final_text_override(context, "")- assert "not saved" in visible+ assert notice in visibleassert context.extension("mastery")["card_posted"] is Falsediff --git a/tests/capabilities/test_mastery_teaching_focus.py b/tests/capabilities/test_mastery_teaching_focus.pyindex fbe57d400..b77946d5d 100644--- a/tests/capabilities/test_mastery_teaching_focus.py+++ b/tests/capabilities/test_mastery_teaching_focus.py@@ -5,13 +5,24 @@ from deeptutor.learning.teaching import teaching_guidancedef test_focus_uses_current_failed_strategy_without_mutating_profile():- profile = LearnerProfile(teaching_observations={- "current": TeachingObservation(knowledge_point_id="point", text="The relationship is unclear",- basis="learner_report", evidence="I still do not see the connection",- strategy="Names without an example", outcome="not_helped"),- "other": TeachingObservation(knowledge_point_id="other", text="Needs a diagram",- strategy="A diagram", outcome="helped"),- })+ profile = LearnerProfile(+ teaching_observations={+ "current": TeachingObservation(+ knowledge_point_id="point",+ text="The relationship is unclear",+ basis="learner_report",+ evidence="I still do not see the connection",+ strategy="Names without an example",+ outcome="not_helped",+ ),+ "other": TeachingObservation(+ knowledge_point_id="other",+ text="Needs a diagram",+ strategy="A diagram",+ outcome="helped",+ ),+ }+ )before = profile.model_dump()focus = teaching_guidance(profile, "point", include_history=True)["teaching_focus"]assert focus["knowledge_point_id"] == "point"@@ -32,4 +43,6 @@ def test_preferences_remain_advisory_and_have_clear_boundaries():assert "current explicit request over older preferences" in guidanceassert "pacing as a preference, not a rigid chunk counter" in guidanceassert "requested display format" in guidance- assert "mode authorization, source trust, pending-question identity or mastery credit" in guidance+ assert (+ "mode authorization, source trust, pending-question identity or mastery credit" in guidance+ )