DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): preserve profile fields and bound save recovery
yepyhun1a2cdb5a25a9
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex 9cc66a5e3..b49991d4e 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -279,6 +279,17 @@ class MasteryLoopCapability: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_recordedif 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``@@ -333,6 +344,16 @@ class MasteryLoopCapability:if not self.is_active(context):return Nonestate = context.extension("mastery")+ if state.get("profile_write_pending") and not state.get("profile_repair_requested"):+ state["profile_repair_requested"] = True+ return (+ "The selected mastery_profile update has no successful storage receipt. "+ "If repairable, retry once with the current revision and only the requested "+ "changed fields. Blank optional fields keep existing values. Otherwise continue "+ "the useful teaching, apply the request for this turn, and explain that it was "+ "not saved for future sessions. Do not claim durable persistence without a "+ "successful receipt. Do not delay teaching with repeated optional profile retries."+ )if state.get("quiz_requested") and not state.get("card_posted"):return ("This turn selected mastery_quiz, but no question card was successfully "@@ -404,14 +425,32 @@ class MasteryLoopCapability:if not self.is_active(context):return Nonestate = context.extension("mastery")+ notice = ""+ if state.get("profile_write_pending"):+ # Optional memory failure must not deadlock otherwise valid tutoring.+ # The native status corrects any unsupported persistence promise;+ # it does not classify or discard the learner-facing explanation.+ state["profile_write_pending"] = False+ state["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."+ )++ def with_notice(override):+ if not notice:+ return override+ content = final_text if override is None else override+ return notice + ("\n\n" + content if content.strip() else "")+if not state.get("card_posted"):- return None+ return with_notice(None)if final_text.strip():# A tool-less finish round already wrote the answer; the card was# posed earlier in the turn and has nothing to override.- return None+ return with_notice(None)state["card_posted"] = False- return ""+ return with_notice("")async def pre_loop(self, context: UnifiedContext, stream: Any, *, usage: Any = Nonediff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex d92ace57a..9e0ca681d 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -2056,12 +2056,15 @@ class MasteryProfileTool(BaseTool):"to them, how much time they have, and how they want it ""taught. Call it during intake — before designing the outline ""— and again whenever they correct one of these. Pass only the "- "fields they actually spoke to; omitted fields keep what they "+ "fields they actually spoke to; omitted, null or blank fields keep what they ""said before. Never invent an answer they did not give. ""For evolving teaching feedback use keyed teaching_updates: explicit ""preferences or objective-local difficulties/attempts. Keep attempts ""unknown until learner evidence shows helped/not_helped. Reuse a key "- "to correct it, remove obsolete entries, preserve unrelated keys."+ "to correct it, remove obsolete entries, preserve unrelated keys. "+ "To forget an intake field explicitly requested by the learner, use clear_fields "+ "and quote that current request in clear_request. Global preferences across "+ "unrelated paths belong in write_memory, only when explicitly requested."),parameters=[ToolParameter(@@ -2116,9 +2119,7 @@ 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 "@@ -2131,10 +2132,17 @@ class MasteryProfileTool(BaseTool):items=TeachingUpdate.model_json_schema(),),ToolParameter(- name="expected_revision",- type="integer",- required=False,- description="Required with teaching_updates: path_revision from the current mastery snapshot. Refresh after conflict.",+ 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,+ 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"]},+ ),+ ToolParameter(+ name="clear_request", type="string", required=False,+ description="Literal quote from the current learner request authorizing clear_fields. Omit unless clearing.",),],)@@ -2154,10 +2162,11 @@ class MasteryProfileTool(BaseTool):"teaching_strategy","notes",)- if key in kwargs and kwargs[key] is not None+ if key in kwargs and kwargs[key] is not None and str(kwargs[key]).strip()}updates = kwargs.get("teaching_updates")- if not fields and updates is None:+ clear_fields = kwargs.get("clear_fields")+ if not fields and updates is None and not clear_fields:return ToolResult(content=("mastery_profile needs at least one of prior_knowledge, "@@ -2180,21 +2189,19 @@ 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 "",)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})return _json_result({"status": "recorded",diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.pyindex 975b75bfd..03e732752 100644--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@ -1285,6 +1285,8 @@ class LearningService:teaching_updates: list[dict] | None = None,expected_revision: int | None = None,learner_message: str = "",+ clear_fields: list[str] | None = None,+ clear_request: str = "",) -> tuple[LearningProgress, list[str]]:"""Merge intake answers into this goal's learner profile.@@ -1301,8 +1303,24 @@ class LearningService:cleaned = {key: str(value or "").strip()[:_MAX_PROFILE_FIELD_LEN]for key, value in fields.items()- if key in _LEARNER_PROFILE_FIELDS and value is not None+ if key in _LEARNER_PROFILE_FIELDS and value is not None and str(value).strip()}+ # Optional schema placeholders are not learner-authored deletions.+ # 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)+ ):+ 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 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:+ raise ValueError("clear_fields requires the current path revision")+ cleaned.update({key: "" for key in clear_fields})from deeptutor.learning.teaching import apply_teaching_updates, parse_teaching_updatesupdates = (@@ -1335,7 +1353,7 @@ class LearningService:changed.extend(teaching_fields)if not changed:return []- if updates and tx.progress.version != expected_revision:+ if (updates or clear_fields) and tx.progress.version != expected_revision:from deeptutor.learning.storage import LearningConflictErrorraise LearningConflictError(book_id, expected_revision, tx.progress.version)@@ -1352,7 +1370,7 @@ class LearningService:)return changed- return self._store.mutate(book_id, record, create=not bool(updates))+ return self._store.mutate(book_id, record, create=not bool(updates or clear_fields))def abandon_active_question(self, book_id: str) -> tuple[LearningProgress, bool]:"""Drop the outstanding question so the path can move on.diff --git a/tests/capabilities/test_mastery_profile_continuity.py b/tests/capabilities/test_mastery_profile_continuity.pynew file mode 100644index 000000000..6d4cf76be--- /dev/null+++ b/tests/capabilities/test_mastery_profile_continuity.py@@ -0,0 +1,124 @@+"""Profile updates preserve standing context across sessions and tool retries."""++import json++import pytest++from deeptutor.capabilities.mastery.tools import MasteryProfileTool, MasteryStatusTool+from deeptutor.learning.models import KnowledgePoint, LearningModule+from deeptutor.learning.service import LearningService+from deeptutor.learning.storage import LearningConflictError, LearningStore+++def 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")])])+ 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")+ return store, service+++async def test_blank_optional_arguments_do_not_erase_intake_during_feedback(system, tmp_path):+ store, service = system+ before = store.load("path")+ 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.",+ }])+ assert result.success, result.content+ loaded = 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})+ assert changed == [] and after.version == loaded.version+++async 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)+ 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"]+++def test_clear_is_explicit_quoted_revision_fenced_and_idempotent(system):+ store, service = system+ revision = store.load("path").version+ request = "Forget my old time budget."+ 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 == ""+ assert progress.learner_profile.preferences == "Use diagrams"+ again, changed = service.record_learner_profile("path", **kwargs)+ assert changed == [] and again.version == progress.version+ with pytest.raises(ValueError, match="literal quote"):+ service.record_learner_profile("path", **{**kwargs, "learner_message": "Teach me next"})+ with pytest.raises(LearningConflictError):+ service.record_learner_profile("path", **{**kwargs, "clear_fields": ["notes"]})+++async def test_selected_profile_write_needs_a_successful_native_receipt(system):+ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.core.context import UnifiedContext++ cap = MasteryLoopCapability()+ 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.success+ assert "mastery_profile" in cap.finish_instruction(context, "Saved for next time.")+ corrected = cap.augment_kwargs("mastery_profile", {"preferences": "Connected explanations"}, context)+ result = await MasteryProfileTool().execute(**corrected)+ assert result.success+ assert cap.finish_instruction(context, "Saved for next time.") is None+ assert context.extension("mastery")["profile_receipt"]["updated_fields"] == ["preferences"]+++async def test_profile_failure_has_one_repair_round_then_teaching_with_unsaved_notice(system):+ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.core.context import UnifiedContext++ cap = 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))+ assert not result.success+ assert 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."+ assert cap.finish_instruction(context, teaching) is None+ visible = cap.final_text_override(context, teaching)+ assert "not saved" in visible and teaching in visible+ assert context.extension("mastery")["profile_receipt"]["status"] == "not_saved"+++def test_unsaved_notice_preserves_card_finish_postcondition():+ from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+ from deeptutor.core.context import UnifiedContext++ context = UnifiedContext(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 context.extension("mastery")["card_posted"] is False