DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery-path): allow editing legacy objective counts (#1790)
KennySimpson8dce2550b2e6
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 4ea4c8084..d583efdfa 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -668,6 +668,9 @@ async def edit_topic_map(path_id: str, body: EditTopicMapRequest):strict=True,existing_module_ids=existing_module_ids,existing_objective_ids=existing_objective_ids,+ existing_objective_counts={+ module.id: len(module.knowledge_points) for module in progress.modules+ },module_limit=MAX_MODULE_LIMIT,)except TopicGenerationError as exc:diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex 67167aabe..d0d97d50b 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -10,7 +10,9 @@ import pytestfrom deeptutor.api.routers.mastery_path import router, ws_routerfrom deeptutor.learning.models import (+ KnowledgePoint,KnowledgeType,+ LearningModule,LearningProgress,PendingQuestion,QuizAttempt,@@ -371,6 +373,81 @@ class TestTopicProductApi:assert progress.mastery_levels == {first_id: 0.2, third_id: 0.9}assert [attempt.question_id for attempt in progress.quiz_attempts] == ["third-evidence"]+ def test_edit_legacy_topic_map_preserves_all_objectives_and_evidence(self, client, app):+ module = LearningModule(+ id="legacy-module",+ name="Legacy region",+ order=0,+ knowledge_points=[+ KnowledgePoint(+ id=f"legacy-kp-{index}",+ name=f"Objective {index}",+ type=KnowledgeType.CONCEPT,+ module_id="legacy-module",+ )+ for index in range(8)+ ],+ )+ progress = LearningProgress(book_id="legacy-path", name="Legacy route", modules=[module])+ last_id = module.knowledge_points[-1].id+ progress.mastery_levels[last_id] = 0.9+ progress.quiz_attempts.append(+ QuizAttempt(+ question_id="legacy-evidence",+ knowledge_point_id=last_id,+ module_id=module.id,+ is_correct=True,+ )+ )+ store = LearningStore(root=app.state.learning_root)+ store.save(progress)+ edited = module.model_dump(mode="json")+ edited["knowledge_points"][0]["type"] = "memory"+ edited["knowledge_points"].reverse()++ response = client.put(+ "/api/mastery-paths/topics/legacy-path/map", json={"modules": [edited]}+ )++ assert response.status_code == 200, response.text+ reloaded = store.load("legacy-path")+ assert reloaded is not None+ updated_points = reloaded.modules[0].knowledge_points+ assert [point.id for point in updated_points[:-1]] == [+ point.id for point in reversed(module.knowledge_points[1:])+ ]+ assert updated_points[-1].id != module.knowledge_points[0].id+ assert updated_points[-1].type == KnowledgeType.MEMORY+ assert reloaded.mastery_levels[last_id] == 0.9+ assert [attempt.question_id for attempt in reloaded.quiz_attempts] == ["legacy-evidence"]++ def test_edit_legacy_topic_map_cannot_add_a_ninth_objective(self, client, app):+ points = [+ KnowledgePoint(+ id=f"legacy-kp-{index}",+ name=f"Objective {index}",+ type=KnowledgeType.CONCEPT,+ module_id="legacy-module",+ )+ for index in range(8)+ ]+ module = LearningModule(+ id="legacy-module", name="Legacy region", order=0, knowledge_points=points+ )+ store = LearningStore(root=app.state.learning_root)+ store.save(LearningProgress(book_id="legacy-path", modules=[module]))+ edited = module.model_dump(mode="json")+ edited["knowledge_points"].append({"name": "New objective", "type": "concept"})++ response = client.put(+ "/api/mastery-paths/topics/legacy-path/map", json={"modules": [edited]}+ )++ assert response.status_code == 422+ reloaded = store.load("legacy-path")+ assert reloaded is not None+ assert len(reloaded.modules[0].knowledge_points) == 8+def test_edit_topic_map_rejects_empty_region_instead_of_silently_dropping_it(self, client):created = client.post("/api/mastery-paths/topics",diff --git a/deeptutor/learning/tests/test_topic_generation.py b/deeptutor/learning/tests/test_topic_generation.pyindex 832b84c4e..d77acac16 100644--- a/deeptutor/learning/tests/test_topic_generation.py+++ b/deeptutor/learning/tests/test_topic_generation.py@@ -51,6 +51,66 @@ def test_edit_reorder_preserves_existing_module_and_objective_ids() -> None:assert [module.order for module in modules] == [0, 1]+ "module_id, counts, count, accepted",+ [+ ("topic_m0", {"topic_m0": 8}, 8, True),+ ("topic_m0", {"topic_m0": 8}, 9, False),+ ("draft-new", {"topic_m0": 8}, 8, False),+ ("draft-new", {"draft-new": 8}, 8, False),+ ("topic_m0", {"topic_m0": 3}, 8, False),+ ("topic_m0", None, 8, False),+ ],+)+def test_legacy_edit_budget_is_bound_to_the_existing_region(+ module_id: str, counts: dict[str, int] | None, count: int, accepted: bool+) -> None:+ points = [(f"kp{index}", f"Objective {index}") for index in range(count)]+ if not accepted:+ with pytest.raises(TopicGenerationError, match="at most .* waypoints"):+ materialize_modules(+ "topic",+ [_module(module_id, *points)],+ strict=True,+ existing_module_ids={"topic_m0"},+ existing_objective_ids={point_id for point_id, _ in points},+ existing_objective_counts=counts,+ )+ return++ modules = materialize_modules(+ "topic",+ [_module(module_id, *reversed(points))],+ strict=True,+ existing_module_ids={"topic_m0"},+ existing_objective_ids={point_id for point_id, _ in points},+ existing_objective_counts=counts,+ )+ assert [point.id for point in modules[0].knowledge_points] == [+ point_id for point_id, _ in reversed(points)+ ]+++def test_duplicate_region_id_does_not_reuse_the_legacy_edit_budget() -> None:+ points = [(f"kp{index}", f"Objective {index}") for index in range(8)]+ raw = [_module("topic_m0", *points), _module("topic_m0", *points)]+ with pytest.raises(TopicGenerationError, match="region 2 may have at most 7 waypoints"):+ materialize_modules(+ "topic",+ raw,+ strict=True,+ existing_module_ids={"topic_m0"},+ existing_objective_ids={point_id for point_id, _ in points},+ existing_objective_counts={"topic_m0": 8},+ )+++def test_new_draft_regions_keep_the_generation_limit() -> None:+ points = [(f"kp{index}", f"Objective {index}") for index in range(8)]+ modules = materialize_modules("topic", [_module("draft", *points)])+ assert len(modules[0].knowledge_points) == 7++def test_new_objective_never_reuses_an_existing_or_deleted_position_id() -> None:raw = [_module(diff --git a/deeptutor/learning/topic_generation.py b/deeptutor/learning/topic_generation.pyindex b77566acb..971f86fef 100644--- a/deeptutor/learning/topic_generation.py+++ b/deeptutor/learning/topic_generation.py@@ -312,6 +312,7 @@ def materialize_modules(strict: bool = False,existing_module_ids: set[str] | None = None,existing_objective_ids: set[str] | None = None,+ existing_objective_counts: dict[str, int] | None = None,discarded_modules: list[dict[str, Any]] | None = None,module_limit: int = DEFAULT_MODULE_LIMIT,) -> list[LearningModule]:@@ -330,6 +331,9 @@ def materialize_modules(Position is presentation state, not identity. Existing ids are acceptedonly when the caller proves they belong to this topic; every new entity getsa collision-proof id so a deleted objective's evidence can never be reused.++ An existing region may retain its stored waypoint count when that exceeds+ the generation limit. This edit budget does not apply to new regions."""cap = max(1, min(int(module_limit or DEFAULT_MODULE_LIMIT), MAX_MODULE_LIMIT))if strict and len(raw_modules) > cap:@@ -384,12 +388,15 @@ def materialize_modules(raise TopicGenerationError(f"Route region {module_index + 1} needs at least one waypoint")- if strict and len(raw_kps) > _MAX_OBJECTIVES_PER_MODULE:+ objective_limit = _MAX_OBJECTIVES_PER_MODULE+ if module_id in allowed_modules and existing_objective_counts is not None:+ objective_limit = max(objective_limit, existing_objective_counts.get(module_id, 0))+ if strict and len(raw_kps) > objective_limit:raise TopicGenerationError(f"Route region {module_index + 1} may have at most "- f"{_MAX_OBJECTIVES_PER_MODULE} waypoints; it has {len(raw_kps)}"+ f"{objective_limit} waypoints; it has {len(raw_kps)}")- for kp_index, raw_kp in enumerate(raw_kps[:_MAX_OBJECTIVES_PER_MODULE]):+ for kp_index, raw_kp in enumerate(raw_kps[:objective_limit]):if not isinstance(raw_kp, dict):if strict:raise TopicGenerationError(