DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): read idle placeholder arguments as omission (#2047)
cgycorey768f81c2c5a3
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex 6a814aca6..10cf782b7 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -2851,6 +2851,8 @@ class MasteryReviseTool(BaseTool):type="integer",description="Commit only: the identifier returned by the reviewed preview.",required=False,+ nullable=True,+ minimum=1,),ToolParameter(name="module_order",@@ -2858,10 +2860,12 @@ class MasteryReviseTool(BaseTool):items={"type": "string"},description=("Preview only: complete requested sequence of existing module IDs. "- "Omit to keep order unchanged; may be used without content edits. "+ "Leave it out or empty to keep the order unchanged; may be used "+ "without content edits. ""Does not rename modules, waive prerequisites, or move the current objective."),required=False,+ nullable=True,),ToolParameter(name="module_id",@@ -2872,6 +2876,7 @@ class MasteryReviseTool(BaseTool):"coordinated multi-module adjustment use 'modules'."),required=False,+ nullable=True,),ToolParameter(name="rewrite",@@ -2882,6 +2887,7 @@ class MasteryReviseTool(BaseTool):"value when omitted."),required=False,+ nullable=True,items=revise_items,),ToolParameter(@@ -2889,6 +2895,7 @@ class MasteryReviseTool(BaseTool):type="array",description=("Knowledge points to append to this module: each {name, type}."),required=False,+ nullable=True,items=add_items,),ToolParameter(@@ -2896,6 +2903,7 @@ class MasteryReviseTool(BaseTool):type="array",description="Knowledge point ids to drop from this module.",required=False,+ nullable=True,items={"type": "string"},),ToolParameter(@@ -2910,6 +2918,7 @@ class MasteryReviseTool(BaseTool):"the learner's request spans multiple modules."),required=False,+ nullable=True,items={"type": "object","properties": {@@ -2941,9 +2950,14 @@ class MasteryReviseTool(BaseTool):from deeptutor.learning.storage import LearningConflictErroraction = kwargs.get("action")+ if isinstance(action, str) and not action.strip():+ # A provider that has to fill every field sends "" for "no action";+ # read it as the omitted action, which is the direct revision.+ action = Noneif action not in (None, "preview", "commit"):return ToolResult(content="Use action preview or commit, or omit it.", success=False)service = _new_service()+ kwargs = _omitting_idle_placeholders(kwargs, commit=action == "commit")if action == "commit":if any(kwargs.get(key) is not None@@ -3422,6 +3436,29 @@ def _plan_module_revision(return applied, targets, revised_by_module, resets_by_module+def _omitting_idle_placeholders(kwargs: dict[str, Any], *, commit: bool) -> dict[str, Any]:+ """Read the fields the model filled only because it had to fill them.++ Endpoints that normalise optional properties into required ones leave the+ model no way to omit a field, so it sends ``0`` / ``""`` / ``[]`` for the+ ones this call does not use (issue #2047). Left as-is, those read as a real+ edit or a real preview id and the call is refused before it is planned.++ Normalized one level deep only: a nested ``prerequisite_ids: []`` is how a+ caller clears a relationship, not a placeholder. ``preview_id`` is idle+ outside commit only — a commit names one preview or nothing.+ """+ cleaned = dict(kwargs)+ # None of the revision arguments has a meaningful falsy value, so falsy is+ # placeholder whatever shape it arrives in (0, "", [], False).+ for key in ("module_order", "module_id", "modules", "rewrite", "add", "remove"):+ if not cleaned.get(key):+ cleaned.pop(key, None)+ if not commit and not cleaned.get("preview_id"):+ cleaned.pop("preview_id", None)+ return cleaned++def _revise_specs(kwargs: dict[str, Any]) -> tuple[dict[str, dict[str, Any]], str | None]:"""Read one revise request into ``{module_id: spec}``, or say why not.diff --git a/tests/capabilities/test_mastery_reviewed_revision.py b/tests/capabilities/test_mastery_reviewed_revision.pyindex dd6c3c98b..87739f85b 100644--- a/tests/capabilities/test_mastery_reviewed_revision.py+++ b/tests/capabilities/test_mastery_reviewed_revision.py@@ -392,7 +392,6 @@ async def test_reorder_only_preview_commit_preserves_every_objective_and_pending@pytest.mark.parametrize("order",[- [],["m0", "m1"],["m0", "m1", "m1"],["m0", "m1", "foreign"],@@ -642,3 +641,188 @@ def test_group_child_revision_is_previewed_without_retiring_live_questions(systeservice.commit_module_revision("path", result["preview_id"], session_id="session")assert store.get_active_interaction("path") is Noneassert store.load("path").pending_question is None+++# #2047: providers that normalise optional properties into required ones make the+# model fill every field, so an unused one arrives as 0 / "" / []. Those are+# absence, not content — unless the field is a nested relationship list, where an+# empty list is how a caller says "clear it".+_PLACEHOLDERS = {+ "preview_id": 0,+ "module_id": "",+ "module_order": [],+ "modules": [],+ "rewrite": [],+ "add": [],+ "remove": [],+}+++def _outline_bound():+ return {+ "_mastery_path_id": "path",+ "_session_id": "session",+ "_mastery_session_mode": "outline",+ }+++async def test_inactive_placeholders_do_not_start_a_preview_as_a_commit(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ result = await MasteryReviseTool().execute(+ action="preview",+ **{**_PLACEHOLDERS, "modules": revisions()[:1]},+ **_outline_bound(),+ )+ assert result.success, result.content+ payload = json.loads(result.content)+ assert payload["status"] == "preview_only_not_saved"+ assert payload["proposed_module_order"] == ["m0", "m1", "m2"]+ assert payload["module_order_changed"] is False+++async def test_commit_takes_the_preview_id_past_inactive_edit_placeholders(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ tool = MasteryReviseTool()+ previewed = await tool.execute(action="preview", modules=revisions()[:1], **_outline_bound())+ assert previewed.success, previewed.content+ preview_id = json.loads(previewed.content)["preview_id"]++ result = await tool.execute(+ action="commit", **{**_PLACEHOLDERS, "preview_id": preview_id}, **_outline_bound()+ )+ assert result.success, result.content+ committed = json.loads(result.content)+ assert committed["status"] == "committed"+ assert committed["replayed"] is False+ assert system[0].load("path").version == committed["path_revision"]++ for bad_id in (0, "", False):+ rejected = await tool.execute(action="commit", preview_id=bad_id, **_outline_bound())+ assert not rejected.success and "preview_id" in rejected.content+++async def test_an_empty_order_alone_is_not_a_silent_no_op(system, monkeypatch):+ """module_order: [] means "unchanged", so a call that carries nothing else still+ has to say what it wants revised."""+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ before = system[0].load("path").version+ result = await MasteryReviseTool().execute(+ action="preview", module_order=[], **_outline_bound()+ )+ assert not result.success and "needs a module_id" in result.content+ assert system[0].load("path").version == before+++async def test_nested_empty_relationships_still_clear_instead_of_vanish(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ result = await MasteryReviseTool().execute(+ action="preview",+ **{+ **_PLACEHOLDERS,+ "modules": [+ {+ "module_id": "m1",+ "rewrite": [+ {+ "knowledge_point_id": "p1",+ "name": "Objective 1",+ "prerequisite_ids": [],+ }+ ],+ }+ ],+ },+ **_outline_bound(),+ )+ assert result.success, result.content+ changes = {c["path"]: c for c in json.loads(result.content)["changes"]}+ cleared = next(c for path, c in changes.items() if path.endswith("/prerequisite_ids"))+ assert cleared["after"] == []+++ "field",+ ["preview_id", "module_order", "module_id", "modules", "rewrite", "add", "remove"],+)+def test_schema_offers_null_for_every_idle_field(field):+ import jsonschema++ schema = MasteryReviseTool().get_definition().to_openai_schema()["function"]["parameters"]+ jsonschema.validate({"action": "commit", field: None}, schema)+++def test_schema_requires_a_positive_commit_preview_id():+ import jsonschema++ schema = MasteryReviseTool().get_definition().to_openai_schema()["function"]["parameters"]+ with pytest.raises(jsonschema.ValidationError):+ jsonschema.validate({"action": "commit", "preview_id": 0}, schema)+++async def test_blank_action_is_read_as_the_omitted_action(system, monkeypatch):+ """#2047 again: a field that must be filled arrives as "" for "not using it"."""+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ result = await MasteryReviseTool().execute(+ action="",+ module_id="m0",+ rewrite=[{"knowledge_point_id": "p0", "name": "Revised objective 0"}],+ **_outline_bound(),+ )+ assert result.success, result.content+ assert json.loads(result.content)["status"] == "revised"++ # A blank action must not become a silent commit: the preview id is still+ # only valid beside action=commit.+ stray = await MasteryReviseTool().execute(+ action="",+ preview_id=7,+ modules=[{"module_id": "m0", "rewrite": revisions()[:1][0]["rewrite"]}],+ **_outline_bound(),+ )+ assert not stray.success and "only with action commit" in stray.content++[email protected]("idle", [0, "", False, 0.0])+async def test_every_shape_of_an_idle_preview_id_is_read_as_absent(system, monkeypatch, idle):+ """The placeholder arrives in whatever type the provider serialises it in."""+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ result = await MasteryReviseTool().execute(+ action="preview", preview_id=idle, modules=revisions()[:1], **_outline_bound()+ )+ assert result.success, result.content+ assert json.loads(result.content)["status"] == "preview_only_not_saved"+++async def test_a_zeroed_module_id_does_not_block_a_commit(system, monkeypatch):+ from deeptutor.capabilities.mastery import tools++ monkeypatch.setattr(tools, "_new_service", lambda: system[1])+ tool = MasteryReviseTool()+ previewed = await tool.execute(action="preview", modules=revisions()[:1], **_outline_bound())+ assert previewed.success, previewed.content+ preview_id = json.loads(previewed.content)["preview_id"]++ result = await tool.execute(+ action="commit", preview_id=preview_id, module_id=0, **_outline_bound()+ )+ assert result.success, result.content+ assert json.loads(result.content)["status"] == "committed"