DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): apply coordinated multi-module revisions atomically (#1929)
XZHcf37be0f5e90
diff --git a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yamlindex 519021a8d..f5ae6c25a 100644--- a/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/en/mastery_loop.yaml@@ -63,7 +63,7 @@ session:**This mode is for designing this mastery goal's outline with the learner, not for teaching.**This mode has exactly one product: an outline you both agree on. You do not teach content and you do not examine them — the tools for posing questions are refused here.- **Read which of the two `mastery_status` is describing.** `status: empty` means this goal has no outline yet and your job is the **first draft**; `status: active` means an outline already exists and the learner agreed to it, so your job is to **change** it — `mastery_revise` on the smallest piece that is wrong, not `mastery_build` over the whole thing. Those are entirely different experiences on their side; do not confuse them.+ **Read which of the two `mastery_status` is describing.** `status: empty` means this goal has no outline yet and your job is the **first draft**; `status: active` means an outline already exists and the learner agreed to it, so your job is to **change** it — `mastery_revise` on the smallest piece that is wrong, not `mastery_build` over the whole thing. Those are entirely different experiences on their side; do not confuse them. When one coordinated change touches several modules, make it a single `mastery_revise` call with `modules=[...]`: they are revised together in one atomic change and one report, instead of replaying the whole outline once per module.Every round, `mastery_status` gives you `path_name` and `goal` — `goal` is what the learner wrote themselves when they created this. **You are already standing in that goal**: never ask which learning route they mean, never list their other goals for them to choose from, and never `mastery_switch` away. This is the one they opened.diff --git a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yamlindex 8ffcb6a95..731b0cd67 100644--- a/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml+++ b/deeptutor/capabilities/mastery/prompts/zh/mastery_loop.yaml@@ -61,7 +61,7 @@ session:**这个模式是用来和学习者一起定下这条精通之路的大纲的,不是用来上课的。**这个模式只有一个产物:一份两人都认可的大纲。你不教内容,也不考他——出题的工具在这个模式下会被拒绝。- **先看 `mastery_status` 告诉你的是哪一种。** `status` 是 `empty` 说明这个目标还没有大纲,你要做的是**从零起草第一版**;`status` 是 `active` 说明大纲已经存在、学习者认可过,你要做的是**改动它**,那就用 `mastery_revise` 动最小的一块,而不是 `mastery_build` 整张换掉。这两件事在学习者那里是完全不同的体验,别搞混。+ **先看 `mastery_status` 告诉你的是哪一种。** `status` 是 `empty` 说明这个目标还没有大纲,你要做的是**从零起草第一版**;`status` 是 `active` 说明大纲已经存在、学习者认可过,你要做的是**改动它**,那就用 `mastery_revise` 动最小的一块,而不是 `mastery_build` 整张换掉。这两件事在学习者那里是完全不同的体验,别搞混。一次协调的改动涉及多个模块时,用一次 `mastery_revise` 调用、传 `modules=[...]` 一起改:它们会作为一次原子变更一并生效、只回一份报告,而不是每个模块都把整张大纲重播一遍。`mastery_status` 每一轮都会告诉你 `path_name` 和 `goal`——`goal` 就是学习者创建这个目标时亲手写下的话。**你已经站在这个目标里了**:绝不要问他「你想聊哪条学习路线」,也不要列出他别的目标让他选,更不要 `mastery_switch` 到别处去。他点进来的就是这一个。diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex d988ccaf0..16be981f4 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -2167,6 +2167,41 @@ class MasteryReviseTool(BaseTool):"""def get_definition(self) -> ToolDefinition:+ revise_items = {+ "type": "object",+ "properties": {+ "knowledge_point_id": {"type": "string"},+ "name": {"type": "string"},+ "type": {"type": "string", "enum": sorted(_ALLOWED_KP_TYPES)},+ "prerequisite_ids": {+ "type": "array",+ "items": {"type": "string"},+ "description": ("Omit to inherit; [] explicitly clears required objectives."),+ },+ "topic_source_ids": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Omit to inherit; [] explicitly clears sources.",+ },+ },+ "required": ["knowledge_point_id", "name"],+ }+ add_items = {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "type": {"type": "string", "enum": sorted(_ALLOWED_KP_TYPES)},+ "prerequisite_ids": {+ "type": "array",+ "items": {"type": "string"},+ },+ "topic_source_ids": {+ "type": "array",+ "items": {"type": "string"},+ },+ },+ "required": ["name"],+ }return ToolDefinition(name="mastery_revise",description=(@@ -2180,15 +2215,22 @@ class MasteryReviseTool(BaseTool):"so and offer mastery_build instead of quietly widening the ""module. Rewriting a knowledge point resets its progress; a ""knowledge point the learner has already mastered cannot be "- "rewritten or removed."+ "rewritten or removed. When one coordinated adjustment touches "+ "SEVERAL modules, pass them together as modules=[{module_id, "+ "rewrite, add, remove}, ...] in ONE call — they are applied, "+ "validated and reported as a single atomic revision, instead "+ "of one full-outline round per module."),parameters=[ToolParameter(name="module_id",type="string",description=(- "Which module to revise. Copy it verbatim from mastery_status's map."+ "Which module to revise. Copy it verbatim from "+ "mastery_status's map. Single-module form only; for a "+ "coordinated multi-module adjustment use 'modules'."),+ required=False,),ToolParameter(name="rewrite",@@ -2199,43 +2241,14 @@ class MasteryReviseTool(BaseTool):"value when omitted."),required=False,- items={- "type": "object",- "properties": {- "knowledge_point_id": {"type": "string"},- "name": {"type": "string"},- "type": {"type": "string", "enum": sorted(_ALLOWED_KP_TYPES)},- "prerequisite_ids": {- "type": "array",- "items": {"type": "string"},- "description": (- "Omit to inherit; [] explicitly clears required objectives."- ),- },- "topic_source_ids": {- "type": "array",- "items": {"type": "string"},- "description": "Omit to inherit; [] explicitly clears sources.",- },- },- "required": ["knowledge_point_id", "name"],- },+ items=revise_items,),ToolParameter(name="add",type="array",description=("Knowledge points to append to this module: each {name, type}."),required=False,- items={- "type": "object",- "properties": {- "name": {"type": "string"},- "type": {"type": "string", "enum": sorted(_ALLOWED_KP_TYPES)},- "prerequisite_ids": {"type": "array", "items": {"type": "string"}},- "topic_source_ids": {"type": "array", "items": {"type": "string"}},- },- "required": ["name"],- },+ items=add_items,),ToolParameter(name="remove",@@ -2244,6 +2257,35 @@ class MasteryReviseTool(BaseTool):required=False,items={"type": "string"},),+ ToolParameter(+ name="modules",+ type="array",+ description=(+ "Coordinated revisions for several modules, applied "+ "together in one atomic revision: each entry "+ "{module_id, rewrite, add, remove} with the same item "+ "shapes as the single-module parameters. Use this "+ "instead of one mastery_revise call per module when "+ "the learner's request spans multiple modules."+ ),+ required=False,+ items={+ "type": "object",+ "properties": {+ "module_id": {"type": "string"},+ "rewrite": {+ "type": "array",+ "items": revise_items,+ },+ "add": {"type": "array", "items": add_items},+ "remove": {+ "type": "array",+ "items": {"type": "string"},+ },+ },+ "required": ["module_id"],+ },+ ),],)@@ -2255,22 +2297,31 @@ class MasteryReviseTool(BaseTool):if not path_id:return _no_path_result()+ specs, spec_error = _revise_specs(kwargs)+ if spec_error is not None:+ return ToolResult(content=spec_error, success=False)+service = _new_service()progress = _load_path(service, path_id)if progress is None or not progress.modules:return _no_built_path_result("mastery_revise")- module_id = str(kwargs.get("module_id") or "").strip()- target = next((m for m in progress.modules if m.id == module_id), None)- if target is None:- known = ", ".join(f"{m.id!r} ({m.name})" for m in progress.modules)- return ToolResult(- content=(f"No module {module_id!r} in this mastery goal. Revise one of: {known}."),- success=False,- )+ known_modules = {m.id: m for m in progress.modules}+ targets: list[LearningModule] = []+ for module_id in specs:+ target = known_modules.get(module_id)+ if target is None:+ known = ", ".join(f"{m.id!r} ({m.name})" for m in progress.modules)+ return ToolResult(+ content=(+ f"No module {module_id!r} in this mastery goal. Revise one of: {known}."+ ),+ success=False,+ )+ targets.append(target)removals = {- str(raw or "").strip() for raw in (kwargs.get("remove") or []) if str(raw or "").strip()+ str(raw or "").strip() for spec in specs.values() for raw in (spec.get("remove") or [])}blocked_by = [f"{point.name!r} ({point.id})"@@ -2288,13 +2339,25 @@ class MasteryReviseTool(BaseTool):success=False,)- revised, error, reset_names, rewrite_ids = _revise_points(progress, target, kwargs)- if error:- return ToolResult(content=error, success=False)+ taken = {kp.id for m in progress.modules for kp in m.knowledge_points}+ revised_by_module: dict[str, list[KnowledgePoint]] = {}+ resets_by_module: dict[str, list[str]] = {}+ rewrite_ids: dict[str, str] = {}+ for target in targets:+ revised, error, resets, rewrites = _revise_points(+ progress, target, specs[target.id], taken=taken+ )+ if error:+ # First rejection refuses the whole request: a coordinated+ # edit must not half-apply because its third module was bad.+ return ToolResult(content=error, success=False)+ revised_by_module[target.id] = revised+ resets_by_module[target.id] = resets+ rewrite_ids.update(rewrites)applied = [- module.model_copy(deep=True, update={"knowledge_points": revised})- if module.id == target.id+ module.model_copy(deep=True, update={"knowledge_points": revised_by_module[module.id]})+ if module.id in revised_by_moduleelse module.model_copy(deep=True)for module in sorted(progress.modules, key=lambda m: m.order)]@@ -2314,15 +2377,14 @@ class MasteryReviseTool(BaseTool):)except ObjectiveRelationError as exc:return ToolResult(content=str(exc), success=False)- return _json_result(- {- "status": "revised",- "path_revision": progress.version,- "module_id": target.id,- "module_name": target.name,++ def _module_report(module: LearningModule, points: list[KnowledgePoint]) -> dict[str, Any]:+ return {+ "module_id": module.id,+ "module_name": module.name,# Echoed so the tutor reports the revision against the promise# it was allowed to keep, not against its own recollection.- "module_objective": target.objective,+ "module_objective": module.objective,"knowledge_points": [{"id": kp.id,@@ -2331,9 +2393,33 @@ class MasteryReviseTool(BaseTool):"prerequisite_ids": kp.prerequisite_ids,"topic_source_ids": kp.topic_source_ids,}- for kp in revised+ for kp in points+ ],+ }++ if len(targets) == 1:+ target = targets[0]+ return _json_result(+ {+ "status": "revised",+ "path_revision": progress.version,+ **_module_report(target, revised_by_module[target.id]),+ "progress_reset": resets_by_module[target.id],+ "map": map_summary(progress),+ },+ meta_key="mastery_revise",+ )+ # One payload — one outline map and one report per touched module —+ # instead of a full snapshot per module echoing through later rounds.+ return _json_result(+ {+ "status": "revised",+ "path_revision": progress.version,+ "modules": [+ _module_report(target, revised_by_module[target.id])+ | {"progress_reset": resets_by_module[target.id]}+ for target in targets],- "progress_reset": reset_names,"map": map_summary(progress),},meta_key="mastery_revise",@@ -2616,10 +2702,62 @@ def _revised_point_id(module_id: str, taken: set[str]) -> str:index += 1+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.++ Two doors into the same contract: the single-module form (``module_id``+ with ``rewrite`` / ``add`` / ``remove`` beside it) and the coordinated+ form (``modules`` holding those per module). Keeping them one shape here+ is what lets one execution path validate and apply both identically —+ and refuses mixing the two, because a half-half request has no single+ meaning to report back.+ """+ batch = kwargs.get("modules")+ single_id = str(kwargs.get("module_id") or "").strip()+ if batch is not None and not isinstance(batch, list):+ return {}, "'modules' must be a list of {module_id, rewrite, add, remove} objects."+ if batch:+ if single_id:+ return {}, (+ "Pass either module_id (one module) or modules (several), not both — "+ "put every coordinated change in its modules entry instead."+ )+ specs: dict[str, dict[str, Any]] = {}+ for raw in batch:+ if not isinstance(raw, dict):+ return {}, "Each modules entry must be an object with a module_id."+ module_id = str(raw.get("module_id") or "").strip()+ if not module_id:+ return {}, "Each modules entry needs the module_id it revises."+ if module_id in specs:+ return {}, (+ f"Module {module_id!r} appears twice in modules. Merge its "+ "rewrite / add / remove changes into one entry."+ )+ spec = {key: raw.get(key) for key in ("rewrite", "add", "remove")}+ if not any(spec.get(key) for key in ("rewrite", "add", "remove")):+ return {}, (+ f"The modules entry for {module_id!r} needs at least one of "+ "rewrite, add or remove."+ )+ specs[module_id] = spec+ return specs, None+ if not single_id:+ return {}, (+ "mastery_revise needs a module_id (one module) or a modules list "+ "(several) saying what to revise."+ )+ has_changes = any(kwargs.get(key) for key in ("rewrite", "add", "remove"))+ if not has_changes:+ return {}, "mastery_revise needs at least one of rewrite, add or remove."+ return {single_id: {key: kwargs.get(key) for key in ("rewrite", "add", "remove")}}, None++def _revise_points(progress: LearningProgress,module: LearningModule,- kwargs: dict[str, Any],+ spec: dict[str, Any],+ taken: set[str] | None = None,) -> tuple[list[KnowledgePoint], str | None, list[str], dict[str, str]]:"""Apply one module's rewrite / add / remove instructions.@@ -2628,16 +2766,19 @@ def _revise_points(because a tool that only says "no" is one the model retries verbatim.``reset_names`` are the knowledge points whose progress this revisionclears, so the tutor can tell the learner before they notice it themselves.+ ``taken`` is the id space new points are minted into; a coordinated+ multi-module revision passes one shared set so fresh ids stay unique+ across the whole batch."""rewrites: dict[str, dict[str, Any]] = {}- for raw in kwargs.get("rewrite") or []:+ for raw in spec.get("rewrite") or []:if not isinstance(raw, dict):continuekp_id = str(raw.get("knowledge_point_id") or "").strip()if kp_id:rewrites[kp_id] = raw- removals = {str(raw).strip() for raw in (kwargs.get("remove") or []) if str(raw or "").strip()}- additions = [raw for raw in (kwargs.get("add") or []) if isinstance(raw, (dict, str))]+ removals = {str(raw).strip() for raw in (spec.get("remove") or []) if str(raw or "").strip()}+ additions = [raw for raw in (spec.get("add") or []) if isinstance(raw, (dict, str))]if not rewrites and not removals and not additions:return ([],@@ -2673,7 +2814,8 @@ def _revise_points({},)- taken = {kp.id for m in progress.modules for kp in m.knowledge_points}+ if taken is None:+ taken = {kp.id for m in progress.modules for kp in m.knowledge_points}points: list[KnowledgePoint] = []reset_names: list[str] = []rewrite_ids: dict[str, str] = {}diff --git a/deeptutor/learning/tests/test_mastery_revise_batch.py b/deeptutor/learning/tests/test_mastery_revise_batch.pynew file mode 100644index 000000000..c5bc9436c--- /dev/null+++ b/deeptutor/learning/tests/test_mastery_revise_batch.py@@ -0,0 +1,439 @@+"""Focused regression tests for coordinated (multi-module) ``mastery_revise``.++Upstream #1929: a coordinated outline adjustment used to need one+``mastery_revise`` call per module, each carrying a fresh full-outline+snapshot back into the model loop. The batch form revises several modules in+ONE reviewed request — one transaction, one revision, one result payload —+while the single-module form keeps its exact contract. Everything here runs+offline against a temp store; no LLM is involved."""++from __future__ import annotations++import json++import pytest++from deeptutor.learning.storage import LearningStore+from deeptutor.tools.mastery_tool import MasteryAssessTool, MasteryBuildTool, MasteryReviseTool+++def path_id(tmp_path, monkeypatch):+ """Point the LearningStore at a temp workspace and yield a stable path id."""+ monkeypatch.setattr(LearningStore, "__init__", _store_init_factory(tmp_path))+ return "test_path"+++def _store_init_factory(root):+ def _init(self, root_arg=None): # mirrors LearningStore.__init__ signature+ from pathlib import Path++ self._root = Path(root) / "learning"+ self._root.mkdir(parents=True, exist_ok=True)++ return _init+++async def _build_three_modules(path_id):+ """A path whose three modules have no cross-module prerequisites yet."""+ build = MasteryBuildTool()+ result = await build.execute(+ _mastery_path_id=path_id,+ path_name="命题逻辑入门",+ modules=[+ {+ "name": "布尔基础",+ "objective": "读懂一个真值表并判断两个命题是否等价",+ "knowledge_points": [+ {"name": "真值表", "type": "memory"},+ {"name": "XOR 的意义", "type": "concept"},+ ],+ },+ {+ "name": "联结词",+ "objective": "用与或非改写日常语句",+ "knowledge_points": [{"name": "合取与析取", "type": "concept"}],+ },+ {+ "name": "论证形式",+ "objective": "识别常见的有效论证形式",+ "knowledge_points": [+ {"name": "肯定前件", "type": "memory"},+ {"name": "否定后件", "type": "memory"},+ ],+ },+ ],+ )+ assert result.success, result.content+ return json.loads(result.content)+++def _stored_state(path_id):+ store = LearningStore()+ progress = store.load(path_id)+ assert progress is not None+ return progress, store+++def _module(progress, module_id):+ return next(m for m in progress.modules if m.id == module_id)+++async def test_batch_revises_modules_in_one_revision_and_one_event(path_id):+ """One coordinated request: one commit, one revision, one result payload."""+ built = await _build_three_modules(path_id)+ base_revision = built["path_revision"]++ revised = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "module_id": "test_path_m0",+ "rewrite": [+ {+ "knowledge_point_id": "test_path_m0_kp1",+ "name": "用 XOR 判断两个命题何时等价",+ "type": "procedure",+ }+ ],+ },+ {+ "module_id": "test_path_m2",+ "remove": ["test_path_m2_kp1"],+ "add": [{"name": "假言三段论", "type": "memory"}],+ },+ ],+ )++ assert revised.success, revised.content+ payload = json.loads(revised.content)+ assert payload["status"] == "revised"+ # One revision committed for the whole coordinated request — not one per+ # module.+ assert payload["path_revision"] == base_revision + 1++ # One report per touched module, each against its own stated promise.+ reports = {entry["module_id"]: entry for entry in payload["modules"]}+ assert set(reports) == {"test_path_m0", "test_path_m2"}+ assert reports["test_path_m0"]["module_objective"] == "读懂一个真值表并判断两个命题是否等价"+ assert reports["test_path_m0"]["progress_reset"] == ["XOR 的意义"]+ assert reports["test_path_m2"]["progress_reset"] == []+ assert [kp["name"] for kp in reports["test_path_m0"]["knowledge_points"]] == [+ "真值表",+ "用 XOR 判断两个命题何时等价",+ ]+ assert [kp["name"] for kp in reports["test_path_m2"]["knowledge_points"]] == [+ "肯定前件",+ "假言三段论",+ ]++ # The payload carries ONE full-outline map for the whole batch.+ assert isinstance(payload["map"]["modules"], list)+ assert len(payload["map"]["modules"]) == 3++ # Exactly one journal event for the whole coordinated request.+ progress, store = _stored_state(path_id)+ assert progress.version == base_revision + 1+ events = store.list_events(path_id, after_revision=base_revision)+ assert [event.event_type for event in events] == ["path.module_revised"]+ assert events[0].payload["module_count"] == 3++ # The stored outline reflects both modules' changes and nothing else.+ assert [kp.name for kp in _module(progress, "test_path_m0").knowledge_points] == [+ "真值表",+ "用 XOR 判断两个命题何时等价",+ ]+ assert [kp.name for kp in _module(progress, "test_path_m1").knowledge_points] == ["合取与析取"]+ assert [kp.name for kp in _module(progress, "test_path_m2").knowledge_points] == [+ "肯定前件",+ "假言三段论",+ ]+++async def test_batch_unknown_module_refuses_the_whole_request(path_id):+ """A bad module id rejects the coordinated edit, not just its entry."""+ built = await _build_three_modules(path_id)+ base_revision = built["path_revision"]++ refused = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "module_id": "test_path_m0",+ "rewrite": [{"knowledge_point_id": "test_path_m0_kp0", "name": "真值表基础"}],+ },+ {+ "module_id": "test_path_m9",+ "add": [{"name": "不存在的模块"}],+ },+ ],+ )++ assert refused.success is False+ assert "test_path_m9" in refused.content+ progress, store = _stored_state(path_id)+ # The valid entry was not applied either: the request is all-or-nothing.+ assert [kp.name for kp in _module(progress, "test_path_m0").knowledge_points] == [+ "真值表",+ "XOR 的意义",+ ]+ assert progress.version == base_revision+ assert store.list_events(path_id, after_revision=base_revision) == []+++async def test_batch_cycle_rolls_back_to_untouched_state(path_id):+ """A cross-module prerequisite cycle rejects the whole plan at commit time."""+ build = MasteryBuildTool()+ built = json.loads(+ (+ await build.execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "name": "Foundations",+ "knowledge_points": [{"name": "Sets"}],+ },+ {+ "name": "Relations",+ "knowledge_points": [+ {"name": "Functions", "prerequisite_refs": ["test_path_m0_kp0"]}+ ],+ },+ ],+ )+ ).content+ )+ base_revision = built["path_revision"]++ refused = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "module_id": "test_path_m0",+ # Sets now depends on Functions…+ "rewrite": [+ {+ "knowledge_point_id": "test_path_m0_kp0",+ "name": "Sets and subsets",+ "prerequisite_ids": ["test_path_m1_kp0"],+ }+ ],+ },+ {+ "module_id": "test_path_m1",+ # …and Functions (rewritten) still depends on the rewritten+ # Sets, referenced by its pre-revision id.+ "rewrite": [+ {+ "knowledge_point_id": "test_path_m1_kp0",+ "name": "Functions and maps",+ "prerequisite_ids": ["test_path_m0_kp0"],+ }+ ],+ },+ ],+ )++ assert refused.success is False+ assert "cycle" in refused.content.lower()+ progress, store = _stored_state(path_id)+ # Rollback is whole-plan: neither module moved, ids included.+ assert [kp.id for kp in _module(progress, "test_path_m0").knowledge_points] == [+ "test_path_m0_kp0"+ ]+ assert [kp.id for kp in _module(progress, "test_path_m1").knowledge_points] == [+ "test_path_m1_kp0"+ ]+ assert _module(progress, "test_path_m1").knowledge_points[0].prerequisite_ids == [+ "test_path_m0_kp0"+ ]+ assert progress.version == base_revision+ assert store.list_events(path_id, after_revision=base_revision) == []+++async def test_batch_shares_id_space_and_remaps_cross_module_prereqs(path_id):+ """Rewrites across modules mint non-colliding ids and re-point edges."""+ build = MasteryBuildTool()+ built = json.loads(+ (+ await build.execute(+ _mastery_path_id=path_id,+ modules=[+ {"name": "Foundations", "knowledge_points": [{"name": "Sets"}]},+ {+ "name": "Relations",+ "knowledge_points": [+ {"name": "Functions", "prerequisite_refs": ["test_path_m0_kp0"]}+ ],+ },+ ],+ )+ ).content+ )+ base_revision = built["path_revision"]++ revised = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "module_id": "test_path_m0",+ "rewrite": [{"knowledge_point_id": "test_path_m0_kp0", "name": "Sets and subsets"}],+ },+ {+ "module_id": "test_path_m1",+ "rewrite": [+ {"knowledge_point_id": "test_path_m1_kp0", "name": "Functions and maps"}+ ],+ },+ ],+ )+ assert revised.success, revised.content+ payload = json.loads(revised.content)+ assert payload["path_revision"] == base_revision + 1++ foundations = payload["map"]["modules"][0]["knowledge_points"]+ relations = payload["map"]["modules"][1]["knowledge_points"]+ new_sets_id = foundations[0]["id"]+ assert new_sets_id != "test_path_m0_kp0"+ assert relations[0]["id"] != "test_path_m1_kp0"+ # A shared id space: the two fresh ids differ even though both modules+ # minted their first rewrite at the same time.+ assert new_sets_id != relations[0]["id"]+ # The inherited cross-module edge follows the rewritten target, without+ # the model having to know the new id in advance.+ assert relations[0]["prerequisite_ids"] == [new_sets_id]++ progress, _ = _stored_state(path_id)+ stored_relations = _module(progress, "test_path_m1").knowledge_points[0]+ assert stored_relations.prerequisite_ids == [new_sets_id]+++async def test_batch_refuses_when_any_module_touches_mastered_work(path_id):+ """Proven work in ANY module of the batch refuses the whole request."""+ built = await _build_three_modules(path_id)+ assessed = await MasteryAssessTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id="test_path_m1_kp0",+ passed=True,+ feedback="学习者用自己的话说清了合取与析取的区别。",+ )+ assert json.loads(assessed.content)["mastered"] is True+ _, store = _stored_state(path_id)+ post_assess_revision = store.load(path_id).version+ assert post_assess_revision > built["path_revision"]++ refused = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ modules=[+ {+ "module_id": "test_path_m0",+ "add": [{"name": "德摩根定律", "type": "memory"}],+ },+ {+ "module_id": "test_path_m1",+ "rewrite": [{"knowledge_point_id": "test_path_m1_kp0", "name": "与或非的日常说法"}],+ },+ ],+ )++ assert refused.success is False+ assert "already mastered" in refused.content+ progress, store = _stored_state(path_id)+ # The other module's addition was refused with it: one request, one verdict.+ assert [kp.name for kp in _module(progress, "test_path_m0").knowledge_points] == [+ "真值表",+ "XOR 的意义",+ ]+ assert [kp.name for kp in _module(progress, "test_path_m1").knowledge_points] == ["合取与析取"]+ assert progress.version == post_assess_revision+ assert all(+ event.event_type != "path.module_revised"+ for event in store.list_events(path_id, after_revision=post_assess_revision)+ )+++async def test_single_module_form_keeps_its_contract(path_id):+ """The original one-module call still returns its original payload shape."""+ built = await _build_three_modules(path_id)+ base_revision = built["path_revision"]++ revised = await MasteryReviseTool().execute(+ _mastery_path_id=path_id,+ module_id="test_path_m1",+ rewrite=[{"knowledge_point_id": "test_path_m1_kp0", "name": "合取、析取与否定"}],+ )++ assert revised.success, revised.content+ payload = json.loads(revised.content)+ assert set(payload) == {+ "status",+ "path_revision",+ "module_id",+ "module_name",+ "module_objective",+ "knowledge_points",+ "progress_reset",+ "map",+ }+ assert payload["module_id"] == "test_path_m1"+ assert payload["progress_reset"] == ["合取与析取"]+ assert [kp["name"] for kp in payload["knowledge_points"]] == ["合取、析取与否定"]++ progress, store = _stored_state(path_id)+ assert progress.version == base_revision + 1+ assert [e.event_type for e in store.list_events(path_id, after_revision=base_revision)] == [+ "path.module_revised"+ ]+++async def test_batch_rejects_malformed_requests(path_id):+ """Shape errors are named, and none of them touches stored state."""+ built = await _build_three_modules(path_id)+ base_revision = built["path_revision"]++ cases = [+ # Mixing the two forms has no single meaning.+ (+ {+ "module_id": "test_path_m0",+ "modules": [{"module_id": "test_path_m1", "add": [{"name": "冗余"}]}],+ },+ "not both",+ ),+ # Same module twice would race itself for one outline slot.+ (+ {+ "modules": [+ {"module_id": "test_path_m0", "add": [{"name": "甲"}]},+ {"module_id": "test_path_m0", "remove": ["test_path_m0_kp0"]},+ ]+ },+ "appears twice",+ ),+ # An entry that changes nothing is a request to do nothing.+ (+ {"modules": [{"module_id": "test_path_m0"}]},+ "at least one of rewrite, add or remove",+ ),+ # Without a module_id there is nothing to revise.+ ({"modules": [{"add": [{"name": "无名模块"}]}]}, "module_id"),+ # And with neither form named at all.+ ({"rewrite": []}, "mastery_revise needs"),+ ]++ tool = MasteryReviseTool()+ for kwargs, expected in cases:+ refused = await tool.execute(_mastery_path_id=path_id, **kwargs)+ assert refused.success is False, (kwargs, refused.content)+ assert expected in refused.content, (kwargs, refused.content)++ progress, store = _stored_state(path_id)+ assert progress.version == base_revision+ assert store.list_events(path_id, after_revision=base_revision) == []