Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(learning): persist mastery prerequisites and topic-source links (#1476)

XZH62032ad7e0ec
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index b49c68cc9..eadf23b08 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -27,6 +27,11 @@ from deeptutor.learning.models import (
TopicSource,
TopicSourceKind,
)
+from deeptutor.learning.objective_relations import (
+ ObjectiveRelationError,
+ RelationRefs,
+ normalize_refs,
+)
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
from deeptutor.learning.topic_generation import MAX_MODULE_LIMIT
@@ -160,8 +165,29 @@ async def _exclusive_path_mutation(book_id: str):
# ── Request models ───────────────────────────────────────────────────────────
+class KnowledgePointInput(BaseModel):
+ id: str | None = None
+ client_ref: str = ""
+ name: str = Field(..., min_length=1, max_length=200)
+ type: KnowledgeType = KnowledgeType.CONCEPT
+ module_id: str = ""
+ prerequisite_ids: list[str] = Field(default_factory=list)
+ prerequisite_refs: list[str] = Field(default_factory=list)
+ topic_source_ids: list[str] = Field(default_factory=list)
+ topic_source_refs: list[str] = Field(default_factory=list)
+
+
+class ModuleInput(BaseModel):
+ id: str | None = None
+ name: str = Field(..., min_length=1, max_length=200)
+ order: int | None = None
+ objective: str = Field(default="", max_length=300)
+ pass_threshold: float = 0.7
+ knowledge_points: list[KnowledgePointInput] = Field(default_factory=list)
+
+
class InitModulesRequest(BaseModel):
- modules: list[dict] # list of LearningModule-compatible dicts
+ modules: list[ModuleInput]
class RenamePathRequest(BaseModel):
@@ -181,6 +207,7 @@ class ImportFromBookRequest(BaseModel):
class TopicSourceRequest(BaseModel):
id: str = ""
+ client_ref: str = ""
kind: TopicSourceKind
source_id: str = ""
label: str = Field(..., min_length=1, max_length=200)
@@ -211,11 +238,11 @@ class ConfirmTopicRequest(GenerateTopicDraftRequest):
# The region ceiling is the generator's, not a second opinion: a route
# over a fourteen-document library legitimately has more than eight, and
# this used to reject the very draft the server had just produced.
- modules: list[dict] = Field(default_factory=list, max_length=MAX_MODULE_LIMIT)
+ modules: list[ModuleInput] = Field(default_factory=list, max_length=MAX_MODULE_LIMIT)
class EditTopicMapRequest(BaseModel):
- modules: list[dict] = Field(..., min_length=1, max_length=MAX_MODULE_LIMIT)
+ modules: list[ModuleInput] = Field(..., min_length=1, max_length=MAX_MODULE_LIMIT)
class LearnerOverrideRequest(BaseModel):
@@ -239,6 +266,45 @@ def _topic_sources(items: list[TopicSourceRequest]) -> list[TopicSource]:
]
+def _topic_source_aliases(
+ items: list[TopicSourceRequest], sources: list[TopicSource]
+) -> dict[str, str]:
+ aliases: dict[str, str] = {}
+ for item, source in zip(items, sources, strict=True):
+ alias = item.client_ref.strip()
+ if alias:
+ if alias in aliases and aliases[alias] != source.id:
+ raise ObjectiveRelationError(f"Source reference {alias!r} is ambiguous")
+ aliases[alias] = source.id
+ return aliases
+
+
+def _module_payloads(modules: list[ModuleInput]) -> list[dict]:
+ return [module.model_dump(mode="json") for module in modules]
+
+
+def _relation_refs(
+ inputs: list[ModuleInput], modules: list[LearningModule]
+) -> dict[str, RelationRefs]:
+ refs: dict[str, RelationRefs] = {}
+ for input_module, module in zip(inputs, modules, strict=True):
+ for input_point, point in zip(
+ input_module.knowledge_points, module.knowledge_points, strict=True
+ ):
+ refs[point.id] = RelationRefs(
+ client_ref=input_point.client_ref.strip(),
+ prerequisite_refs=normalize_refs(
+ [*input_point.prerequisite_refs, *input_point.prerequisite_ids],
+ label="prerequisite",
+ ),
+ topic_source_refs=normalize_refs(
+ [*input_point.topic_source_refs, *input_point.topic_source_ids],
+ label="topic source",
+ ),
+ )
+ return refs
+
+
def _review_queue(progress) -> list[dict]:
names = {kp.id: kp.name for module in progress.modules for kp in module.knowledge_points}
return [
@@ -412,11 +478,15 @@ async def create_topic(body: ConfirmTopicRequest):
if body.modules:
try:
modules = materialize_modules(
- path_id, body.modules, strict=True, module_limit=MAX_MODULE_LIMIT
+ path_id,
+ _module_payloads(body.modules),
+ strict=True,
+ module_limit=MAX_MODULE_LIMIT,
)
except TopicGenerationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
sources = _topic_sources(body.sources)
+ source_aliases = _topic_source_aliases(body.sources, sources)
store = LearningStore()
metadata = TopicMetadata(
path_id=path_id,
@@ -436,14 +506,20 @@ async def create_topic(body: ConfirmTopicRequest):
body.goal,
source_labels=[source.label for source in sources],
) or _provisional_name(body.goal)
- progress = await asyncio.to_thread(
- LearningService(store).create_topic,
- path_id,
- name=resolved_name,
- modules=modules,
- metadata=metadata,
- sources=sources,
- )
+ service = LearningService(store)
+ try:
+ progress = await asyncio.to_thread(
+ service.create_topic,
+ path_id,
+ name=resolved_name,
+ modules=modules,
+ metadata=metadata,
+ sources=sources,
+ relation_refs=_relation_refs(body.modules, modules),
+ source_aliases=source_aliases,
+ )
+ except ObjectiveRelationError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
payload = await asyncio.to_thread(_topic_payload, store, path_id)
payload["path_revision"] = progress.version
return payload
@@ -475,7 +551,7 @@ async def edit_topic_map(path_id: str, body: EditTopicMapRequest):
try:
modules = materialize_modules(
path_id,
- body.modules,
+ _module_payloads(body.modules),
strict=True,
existing_module_ids=existing_module_ids,
existing_objective_ids=existing_objective_ids,
@@ -483,12 +559,16 @@ async def edit_topic_map(path_id: str, body: EditTopicMapRequest):
)
except TopicGenerationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
- await asyncio.to_thread(
- LearningService(store).replace_modules_for_path,
- path_id,
- modules,
- event_type="topic.map_edited",
- )
+ try:
+ await asyncio.to_thread(
+ LearningService(store).replace_modules_for_path,
+ path_id,
+ modules,
+ event_type="topic.map_edited",
+ relation_refs=_relation_refs(body.modules, modules),
+ )
+ except ObjectiveRelationError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
return await asyncio.to_thread(_topic_payload, LearningStore(), path_id)
@@ -858,7 +938,7 @@ async def get_progress_sessions(book_id: str):
@router.post("/progress/{book_id}/init-modules")
async def init_modules(book_id: str, body: InitModulesRequest):
_validate_book_id(book_id)
- modules = _parse_modules(body.modules)
+ modules = _parse_modules(_module_payloads(body.modules))
_validate_runnable_modules(modules)
async with _exclusive_path_mutation(book_id):
service = get_learning_service()
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index b910af014..0dd1ab02e 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -57,6 +57,12 @@ from deeptutor.learning.models import (
KnowledgeType,
LearningModule,
PendingQuestion,
+ TopicSourceKind,
+)
+from deeptutor.learning.objective_relations import (
+ ObjectiveRelationError,
+ RelationRefs,
+ normalize_refs,
)
from deeptutor.learning.pending import public_pending_question
from deeptutor.learning.policy import (
@@ -630,6 +636,16 @@ class MasteryStatusTool(BaseTool):
"path_id": path_id,
"path_name": path_display_name(progress) if progress is not None else "",
"goal": str(getattr(getattr(topic, "metadata", None), "goal", "") or ""),
+ "sources": [
+ {
+ "id": source.id,
+ "kind": source.kind.value,
+ "label": source.label,
+ "available": source.available,
+ }
+ for source in getattr(topic, "sources", [])
+ if source.kind != TopicSourceKind.GOAL
+ ],
}
if progress is None or not any(module.knowledge_points for module in progress.modules):
return _json_result(
@@ -1345,6 +1361,28 @@ class MasteryBuildTool(BaseTool):
"type": "string",
"enum": sorted(_ALLOWED_KP_TYPES),
},
+ "client_ref": {
+ "type": "string",
+ "description": (
+ "Request-local alias for this new knowledge "
+ "point. Use it in prerequisite_refs."
+ ),
+ },
+ "prerequisite_refs": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Required objectives. In append mode use an "
+ "existing map id or a client_ref from this call."
+ ),
+ },
+ "topic_source_refs": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Non-goal source ids reported by mastery_status."
+ ),
+ },
},
"required": ["name"],
},
@@ -1388,7 +1426,7 @@ class MasteryBuildTool(BaseTool):
mode = "replace"
service = _new_service()
- new_modules, error = _parse_modules(
+ new_modules, relation_refs, error = _parse_modules_with_refs(
kwargs.get("modules"),
path_id,
0,
@@ -1397,15 +1435,20 @@ class MasteryBuildTool(BaseTool):
if error:
return ToolResult(content=error, success=False)
- progress = service.replace_modules_for_path(
- path_id,
- new_modules,
- append=mode == "append",
- name=str(kwargs.get("path_name") or ""),
- event_type="path.built",
- session_id=_resolve_session_id(kwargs),
- turn_id=_resolve_turn_id(kwargs),
- )
+ try:
+ progress = service.replace_modules_for_path(
+ path_id,
+ new_modules,
+ append=mode == "append",
+ name=str(kwargs.get("path_name") or ""),
+ event_type="path.built",
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ relation_refs=relation_refs,
+ fresh_identity=mode != "append",
+ )
+ except ObjectiveRelationError as exc:
+ return ToolResult(content=str(exc), success=False)
kp_count = sum(len(m.knowledge_points) for m in new_modules)
return _json_result(
{
@@ -1688,6 +1731,18 @@ class MasteryReviseTool(BaseTool):
"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"],
},
@@ -1702,6 +1757,8 @@ class MasteryReviseTool(BaseTool):
"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"],
},
@@ -1738,7 +1795,26 @@ class MasteryReviseTool(BaseTool):
success=False,
)
- revised, error, reset_names = _revise_points(progress, target, kwargs)
+ removals = {
+ str(raw or "").strip() for raw in (kwargs.get("remove") or []) if str(raw or "").strip()
+ }
+ blocked_by = [
+ f"{point.name!r} ({point.id})"
+ for module in progress.modules
+ for point in module.knowledge_points
+ if point.id not in removals and any(ref in removals for ref in point.prerequisite_ids)
+ ]
+ if blocked_by:
+ return ToolResult(
+ content=(
+ "Those knowledge points are still required by: "
+ + ", ".join(blocked_by)
+ + ". Remove or change those prerequisites first."
+ ),
+ success=False,
+ )
+
+ revised, error, reset_names, rewrite_ids = _revise_points(progress, target, kwargs)
if error:
return ToolResult(content=error, success=False)
@@ -1748,13 +1824,21 @@ class MasteryReviseTool(BaseTool):
else module.model_copy(deep=True)
for module in sorted(progress.modules, key=lambda m: m.order)
]
- progress = service.replace_modules_for_path(
- path_id,
- applied,
- event_type="path.module_revised",
- session_id=_resolve_session_id(kwargs),
- turn_id=_resolve_turn_id(kwargs),
- )
+ for module in applied:
+ for point in module.knowledge_points:
+ point.prerequisite_ids = [
+ rewrite_ids.get(ref, ref) for ref in point.prerequisite_ids
+ ]
+ try:
+ progress = service.replace_modules_for_path(
+ path_id,
+ applied,
+ event_type="path.module_revised",
+ session_id=_resolve_session_id(kwargs),
+ turn_id=_resolve_turn_id(kwargs),
+ )
+ except ObjectiveRelationError as exc:
+ return ToolResult(content=str(exc), success=False)
return _json_result(
{
"status": "revised",
@@ -1765,7 +1849,14 @@ class MasteryReviseTool(BaseTool):
# it was allowed to keep, not against its own recollection.
"module_objective": target.objective,
"knowledge_points": [
- {"id": kp.id, "name": kp.name, "type": kp.type.value} for kp in revised
+ {
+ "id": kp.id,
+ "name": kp.name,
+ "type": kp.type.value,
+ "prerequisite_ids": kp.prerequisite_ids,
+ "topic_source_ids": kp.topic_source_ids,
+ }
+ for kp in revised
],
"progress_reset": reset_names,
"map": map_summary(progress),
@@ -2054,10 +2145,10 @@ def _revise_points(
progress: LearningProgress,
module: LearningModule,
kwargs: dict[str, Any],
-) -> tuple[list[KnowledgePoint], str | None, list[str]]:
+) -> tuple[list[KnowledgePoint], str | None, list[str], dict[str, str]]:
"""Apply one module's rewrite / add / remove instructions.
- Returns ``(points, error, reset_names)``. ``error`` is a sentence for the
+ Returns ``(points, error, reset_names, rewrite_ids)``. ``error`` is a sentence for the
model — every rejection says what was wrong *and* what to do instead,
because a tool that only says "no" is one the model retries verbatim.
``reset_names`` are the knowledge points whose progress this revision
@@ -2077,6 +2168,7 @@ def _revise_points(
[],
"mastery_revise needs at least one of rewrite, add or remove.",
[],
+ {},
)
known = {kp.id for kp in module.knowledge_points}
@@ -2088,6 +2180,7 @@ def _revise_points(
f"Module {module.id!r} has no knowledge point {unknown[0]!r}. Its "
f"knowledge points are: {listed}.",
[],
+ {},
)
protected = sorted(
@@ -2102,11 +2195,19 @@ def _revise_points(
"removed — that would erase proof the learner has earned. Leave it "
"in place and add a new knowledge point if they want to go further.",
[],
+ {},
)
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] = {}
+
+ def relation_values(raw: dict[str, Any], key: str, current: list[str]) -> list[str]:
+ if key not in raw or raw[key] is None:
+ return list(current)
+ return normalize_refs(raw[key], label=key)
+
for kp in module.knowledge_points:
if kp.id in removals:
continue
@@ -2120,6 +2221,7 @@ def _revise_points(
[],
f"The rewrite for {kp.name!r} needs a 'name' of at least two characters.",
[],
+ {},
)
# An unrecognised type keeps the current one: a targeted edit that
# silently retyped a waypoint would change which gate it has to clear.
@@ -2131,8 +2233,11 @@ def _revise_points(
name=name,
type=resolved,
module_id=module.id,
+ prerequisite_ids=relation_values(raw, "prerequisite_ids", kp.prerequisite_ids),
+ topic_source_ids=relation_values(raw, "topic_source_ids", kp.topic_source_ids),
)
)
+ rewrite_ids[kp.id] = points[-1].id
reset_names.append(kp.name)
for raw in additions:
@@ -2150,6 +2255,16 @@ def _revise_points(
name=name,
type=KnowledgeType(kp_type),
module_id=module.id,
+ prerequisite_ids=(
+ normalize_refs(raw.get("prerequisite_ids"), label="prerequisite")
+ if isinstance(raw, dict)
+ else []
+ ),
+ topic_source_ids=(
+ normalize_refs(raw.get("topic_source_ids"), label="topic source")
+ if isinstance(raw, dict)
+ else []
+ ),
)
)
@@ -2160,6 +2275,7 @@ def _revise_points(
"module needs at least one; remove the module with mastery_build if "
"the learner wants it gone entirely.",
[],
+ {},
)
if len(points) > _MAX_POINTS_PER_MODULE:
return (
@@ -2168,13 +2284,14 @@ def _revise_points(
f"this revision would give {module.name!r} {len(points)}. Drop some, or "
"split the material across modules with mastery_build.",
[],
+ {},
)
- return points, None, reset_names
+ return points, None, reset_names, rewrite_ids
-def _parse_modules(
+def _parse_modules_with_refs(
raw_modules: Any, path_id: str, offset: int, fallback_module_name: str = ""
-) -> tuple[list[LearningModule], str | None]:
+) -> tuple[list[LearningModule], dict[str, RelationRefs], str | None]:
"""Validate the model-designed module tree into engine models.
Ids are generated server-side (``<path>_m<i>_kp<j>``) so the model never
@@ -2182,8 +2299,9 @@ def _parse_modules(
"""
entries = _normalized_module_tree(raw_modules, fallback_module_name or "Objectives")
if not entries:
- return [], _BUILD_SHAPE_ERROR
+ return [], {}, _BUILD_SHAPE_ERROR
modules: list[LearningModule] = []
+ relation_refs: dict[str, RelationRefs] = {}
for i, (raw_name, raw_objective, raw_kps) in enumerate(entries):
index = offset + len(modules)
module_id = f"{path_id}_m{index}"
@@ -2194,10 +2312,20 @@ def _parse_modules(
if len(kp_name) < 2:
continue
kp_type = "concept"
+ prerequisite_refs: list[str] = []
+ topic_source_refs: list[str] = []
+ client_ref = ""
if isinstance(raw_kp, dict):
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
if kp_type not in _ALLOWED_KP_TYPES:
kp_type = "concept"
+ prerequisite_refs = normalize_refs(
+ raw_kp.get("prerequisite_refs"), label="prerequisite"
+ )
+ topic_source_refs = normalize_refs(
+ raw_kp.get("topic_source_refs"), label="topic source"
+ )
+ client_ref = str(raw_kp.get("client_ref") or "").strip()
kps.append(
KnowledgePoint(
id=f"{module_id}_kp{len(kps)}",
@@ -2206,6 +2334,11 @@ def _parse_modules(
module_id=module_id,
)
)
+ relation_refs[kps[-1].id] = RelationRefs(
+ client_ref=client_ref,
+ prerequisite_refs=prerequisite_refs,
+ topic_source_refs=topic_source_refs,
+ )
if not kps:
continue
modules.append(
@@ -2218,8 +2351,17 @@ def _parse_modules(
)
)
if not modules:
- return [], _BUILD_SHAPE_ERROR
- return modules, None
+ return [], {}, _BUILD_SHAPE_ERROR
+ return modules, relation_refs, None
+
+
+def _parse_modules(
+ raw_modules: Any, path_id: str, offset: int, fallback_module_name: str = ""
+) -> tuple[list[LearningModule], str | None]:
+ modules, _relation_refs, error = _parse_modules_with_refs(
+ raw_modules, path_id, offset, fallback_module_name
+ )
+ return modules, error
MASTERY_TOOL_TYPES: tuple[type[BaseTool], ...] = (
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index 3f7d8f12d..fc4e58bd8 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -84,6 +84,11 @@ class KnowledgePoint(BaseModel):
name: str
type: KnowledgeType
module_id: str
+ # Required objectives, not a presentation order. Empty on legacy paths.
+ prerequisite_ids: list[str] = Field(default_factory=list)
+ # Selected non-goal sources that justify this objective. They are curriculum
+ # provenance, not proof of factual correctness or retrieval permission.
+ topic_source_ids: list[str] = Field(default_factory=list)
class LearningModule(BaseModel):
diff --git a/deeptutor/learning/objective_relations.py b/deeptutor/learning/objective_relations.py
new file mode 100644
index 000000000..87361ecb0
--- /dev/null
+++ b/deeptutor/learning/objective_relations.py
@@ -0,0 +1,181 @@
+"""Validation and request-reference handling for mastery objective relations.
+
+Relations are structural metadata in this slice. They do not gate learning or
+retrieval yet, but every writer must leave them internally consistent.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass, field
+from typing import Any
+
+from deeptutor.learning.models import KnowledgePoint, LearningModule, TopicSource, TopicSourceKind
+
+
+class ObjectiveRelationError(ValueError):
+ """Raised when a mutation would leave an invalid objective graph."""
+
+
+@dataclass(frozen=True)
+class RelationRefs:
+ """Request-local references carried alongside provisional objective ids."""
+
+ client_ref: str = ""
+ prerequisite_refs: list[str] = field(default_factory=list)
+ topic_source_refs: list[str] = field(default_factory=list)
+
+
+def normalize_refs(values: Iterable[Any] | None, *, label: str) -> list[str]:
+ refs: list[str] = []
+ seen: set[str] = set()
+ for value in values or ():
+ ref = str(value or "").strip()
+ if not ref or ref in seen:
+ continue
+ seen.add(ref)
+ refs.append(ref)
+ return refs
+
+
+def source_ref_map(
+ sources: Iterable[TopicSource], aliases: Mapping[str, str] | None = None
+) -> dict[str, str]:
+ """Map request-local source aliases and durable source ids to durable ids."""
+
+ resolved: dict[str, str] = {}
+ for source in sources:
+ if source.kind == TopicSourceKind.GOAL:
+ continue
+ if source.id in resolved:
+ raise ObjectiveRelationError(f"Duplicate topic source id {source.id!r}")
+ resolved[source.id] = source.id
+ for alias, source_id in (aliases or {}).items():
+ alias = str(alias or "").strip()
+ if not alias:
+ continue
+ if source_id not in resolved:
+ raise ObjectiveRelationError(
+ f"Source alias {alias!r} names unknown source {source_id!r}"
+ )
+ if alias in resolved and resolved[alias] != source_id:
+ raise ObjectiveRelationError(f"Source reference {alias!r} is ambiguous")
+ resolved[alias] = source_id
+ return resolved
+
+
+def _knowledge_points(modules: Iterable[LearningModule]) -> Iterable[KnowledgePoint]:
+ for module in modules:
+ yield from module.knowledge_points
+
+
+def validate_objective_relations(
+ modules: Iterable[LearningModule], sources: Iterable[TopicSource]
+) -> None:
+ points = list(_knowledge_points(modules))
+ point_ids = {point.id for point in points}
+ if len(point_ids) != len(points):
+ raise ObjectiveRelationError("Knowledge point ids must be unique within a mastery path")
+
+ source_ids = {source.id for source in sources if source.kind != TopicSourceKind.GOAL}
+ names = {point.id: point.name for point in points}
+
+ graph: dict[str, list[str]] = {}
+ for point in points:
+ prerequisites = normalize_refs(point.prerequisite_ids, label="prerequisite")
+ point.prerequisite_ids = prerequisites
+ graph[point.id] = prerequisites
+ topic_sources = normalize_refs(point.topic_source_ids, label="topic source")
+ point.topic_source_ids = topic_sources
+ unknown_sources = [ref for ref in topic_sources if ref not in source_ids]
+ if unknown_sources:
+ raise ObjectiveRelationError(
+ f"Objective {names[point.id]!r} references unknown or goal topic source "
+ f"{unknown_sources[0]!r}"
+ )
+
+ for point_id, prerequisites in graph.items():
+ for prerequisite in prerequisites:
+ if prerequisite == point_id:
+ raise ObjectiveRelationError(
+ f"Objective {names[point_id]!r} cannot be its own prerequisite"
+ )
+ if prerequisite not in graph:
+ raise ObjectiveRelationError(
+ f"Objective {names[point_id]!r} has unknown prerequisite {prerequisite!r}"
+ )
+
+ visiting: set[str] = set()
+ visited: set[str] = set()
+ path: list[str] = []
+
+ def visit(point_id: str) -> None:
+ if point_id in visited:
+ return
+ if point_id in visiting:
+ cycle_start = path.index(point_id)
+ cycle = path[cycle_start:] + [point_id]
+ raise ObjectiveRelationError("Prerequisite cycle: " + " -> ".join(cycle))
+ visiting.add(point_id)
+ path.append(point_id)
+ for prerequisite in graph[point_id]:
+ visit(prerequisite)
+ path.pop()
+ visiting.remove(point_id)
+ visited.add(point_id)
+
+ for point_id in graph:
+ visit(point_id)
+
+
+def resolve_relation_refs(
+ modules: list[LearningModule],
+ relation_refs: Mapping[str, RelationRefs],
+ *,
+ prerequisite_aliases: Mapping[str, str],
+ source_aliases: Mapping[str, str],
+ sources: Iterable[TopicSource],
+) -> None:
+ """Resolve request-local refs into durable ids on the final module tree."""
+
+ source_ids = source_ref_map(sources, source_aliases)
+ for module in modules:
+ for point in module.knowledge_points:
+ refs = relation_refs.get(point.id)
+ if refs is None:
+ continue
+ prerequisites: list[str] = []
+ seen_prerequisites: set[str] = set()
+ for ref in normalize_refs(refs.prerequisite_refs, label="prerequisite"):
+ if ref not in prerequisite_aliases:
+ raise ObjectiveRelationError(
+ f"Objective {point.name!r} has unknown prerequisite ref {ref!r}"
+ )
+ resolved = prerequisite_aliases[ref]
+ if resolved not in seen_prerequisites:
+ seen_prerequisites.add(resolved)
+ prerequisites.append(resolved)
+ point.prerequisite_ids = prerequisites
+
+ topic_sources: list[str] = []
+ seen_sources: set[str] = set()
+ for ref in normalize_refs(refs.topic_source_refs, label="topic source"):
+ if ref not in source_ids:
+ raise ObjectiveRelationError(
+ f"Objective {point.name!r} has unknown topic source ref {ref!r}"
+ )
+ resolved = source_ids[ref]
+ if resolved not in seen_sources:
+ seen_sources.add(resolved)
+ topic_sources.append(resolved)
+ point.topic_source_ids = topic_sources
+
+
+__all__ = [
+ "ObjectiveRelationError",
+ "RelationRefs",
+ "normalize_refs",
+ "resolve_relation_refs",
+ "source_ref_map",
+ "validate_objective_relations",
+]
diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.py
index 453953e49..e9509cf85 100644
--- a/deeptutor/learning/policy.py
+++ b/deeptutor/learning/policy.py
@@ -314,6 +314,8 @@ def map_summary(progress: LearningProgress, *, now: float | None = None) -> dict
"id": kp.id,
"name": kp.name,
"type": kp.type.value,
+ "prerequisite_ids": list(kp.prerequisite_ids),
+ "topic_source_ids": list(kp.topic_source_ids),
"status": status,
"mastery": round(display_mastery(progress, kp), 3),
"mastery_source": mastery_source(progress, kp),
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index 590c27f46..6077a49e8 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -23,6 +23,11 @@ from deeptutor.learning.models import (
TopicMetadata,
TopicSource,
)
+from deeptutor.learning.objective_relations import (
+ RelationRefs,
+ resolve_relation_refs,
+ validate_objective_relations,
+)
from deeptutor.learning.storage import LearningStore
if TYPE_CHECKING:
@@ -84,6 +89,85 @@ class LearningService:
"""Initialize the runnable module set (replace semantics)."""
self.replace_modules(progress, modules)
+ @staticmethod
+ def _new_entity_id(prefix: str, reserved: set[str]) -> str:
+ while True:
+ candidate = f"{prefix}_{uuid.uuid4().hex[:12]}"
+ if candidate not in reserved:
+ reserved.add(candidate)
+ return candidate
+
+ @classmethod
+ def _finalize_modules(
+ cls,
+ progress: LearningProgress,
+ modules: list[LearningModule],
+ *,
+ append: bool,
+ fresh_identity: bool,
+ relation_refs: dict[str, RelationRefs],
+ source_aliases: dict[str, str],
+ sources: list[TopicSource],
+ ) -> list[LearningModule]:
+ applied = [module.model_copy(deep=True) for module in modules]
+ existing_kp_ids = {
+ point.id for module in progress.modules for point in module.knowledge_points
+ }
+ prerequisite_aliases = {key: key for key in existing_kp_ids}
+ old_to_new: dict[str, str] = {}
+
+ if append:
+ offset = len(progress.modules)
+ for index, module in enumerate(applied, start=offset):
+ module.id = f"{progress.book_id}_m{index}"
+ module.order = index
+ for kp_index, point in enumerate(module.knowledge_points):
+ old_id = point.id
+ point.module_id = module.id
+ point.id = f"{module.id}_kp{kp_index}"
+ old_to_new[old_id] = point.id
+ elif fresh_identity and existing_kp_ids:
+ reserved_modules = set(module.id for module in progress.modules) | set(
+ module.id for module in applied
+ )
+ reserved_points = set(existing_kp_ids) | set(
+ point.id for module in applied for point in module.knowledge_points
+ )
+ for index, module in enumerate(applied):
+ module.id = cls._new_entity_id(f"{progress.book_id}_m", reserved_modules)
+ module.order = index
+ for point in module.knowledge_points:
+ old_id = point.id
+ point.module_id = module.id
+ point.id = cls._new_entity_id(f"{module.id}_kp", reserved_points)
+ old_to_new[old_id] = point.id
+ else:
+ for module in applied:
+ for point in module.knowledge_points:
+ old_to_new[point.id] = point.id
+
+ final_refs: dict[str, RelationRefs] = {}
+ for module in applied:
+ for point in module.knowledge_points:
+ final_id = point.id
+ for old_id, new_id in old_to_new.items():
+ if new_id == final_id:
+ specs = relation_refs.get(old_id)
+ if specs is not None:
+ final_refs[final_id] = specs
+ if specs.client_ref:
+ prerequisite_aliases[specs.client_ref] = final_id
+ break
+
+ resolve_relation_refs(
+ applied,
+ final_refs,
+ prerequisite_aliases=prerequisite_aliases,
+ source_aliases=source_aliases,
+ sources=sources,
+ )
+ return applied
+
def replace_modules(self, progress: LearningProgress, modules: list[LearningModule]) -> None:
"""Replace all modules and clean stale KP state."""
new_kp_ids = {kp.id for m in modules for kp in m.knowledge_points}
@@ -664,6 +748,10 @@ class LearningService:
event_type: str = "path.modules_replaced",
session_id: str = "",
turn_id: str = "",
+ relation_refs: dict[str, RelationRefs] | None = None,
+ source_aliases: dict[str, str] | None = None,
+ topic_sources: list[TopicSource] | None = None,
+ fresh_identity: bool = False,
) -> LearningProgress:
"""Install a module set, optionally naming a path that has no name yet.
@@ -677,17 +765,22 @@ class LearningService:
def replace(tx):
if name.strip() and not tx.progress.name.strip():
tx.progress.name = name.strip()[:_MAX_PATH_NAME_LEN]
- applied_modules = [module.model_copy(deep=True) for module in modules]
+ sources = tx.topic_sources() if topic_sources is None else topic_sources
+ applied_modules = self._finalize_modules(
+ tx.progress,
+ modules,
+ append=append,
+ fresh_identity=fresh_identity,
+ relation_refs=relation_refs or {},
+ source_aliases=source_aliases or {},
+ sources=sources,
+ )
if append:
- offset = len(tx.progress.modules)
- for index, module in enumerate(applied_modules, start=offset):
- module.id = f"{book_id}_m{index}"
- module.order = index
- for kp_index, kp in enumerate(module.knowledge_points):
- kp.module_id = module.id
- kp.id = f"{module.id}_kp{kp_index}"
- tx.progress.knowledge_types[kp.id] = kp.type
+ validate_objective_relations([*tx.progress.modules, *applied_modules], sources)
tx.progress.modules.extend(applied_modules)
+ for module in applied_modules:
+ for kp in module.knowledge_points:
+ tx.progress.knowledge_types[kp.id] = kp.type
if not tx.progress.current_module_id and applied_modules:
tx.progress.current_module_id = applied_modules[0].id
tx.progress.current_kp_index = 0
@@ -713,6 +806,7 @@ class LearningService:
else ""
)
+ validate_objective_relations(applied_modules, sources)
self.replace_modules(tx.progress, applied_modules)
objective_locations = {
kp.id: (module.id, kp_index)
@@ -772,6 +866,8 @@ class LearningService:
modules: list[LearningModule],
metadata: TopicMetadata,
sources: list[TopicSource],
+ relation_refs: dict[str, RelationRefs] | None = None,
+ source_aliases: dict[str, str] | None = None,
) -> LearningProgress:
"""Create a confirmed topic, sources, and route in one transaction."""
@@ -780,10 +876,20 @@ class LearningService:
def create(tx):
tx.progress.name = str(name or "").strip()[:_MAX_PATH_NAME_LEN]
- self.replace_modules(tx.progress, [module.model_copy(deep=True) for module in modules])
- tx.progress.current_module_id = modules[0].id if modules else ""
- tx.progress.current_kp_index = 0
tx.put_topic(metadata, sources)
+ applied_modules = self._finalize_modules(
+ tx.progress,
+ modules,
+ append=False,
+ fresh_identity=False,
+ relation_refs=relation_refs or {},
+ source_aliases=source_aliases or {},
+ sources=sources,
+ )
+ validate_objective_relations(applied_modules, sources)
+ self.replace_modules(tx.progress, applied_modules)
+ tx.progress.current_module_id = applied_modules[0].id if applied_modules else ""
+ tx.progress.current_kp_index = 0
tx.touch()
tx.emit(
"topic.created",
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 154dd1b82..dd482db1c 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -314,6 +314,31 @@ class LearningTransaction:
{"source_count": len(sources), "status": metadata.status},
)
+ def topic_sources(self) -> list[TopicSource]:
+ """Read this path's source set on the transaction connection."""
+
+ rows = self._conn.execute(
+ """
+ SELECT * FROM mastery_topic_sources
+ WHERE path_id = ? ORDER BY position ASC, created_at ASC
+ """,
+ (self.progress.book_id,),
+ ).fetchall()
+ return [
+ TopicSource(
+ id=row["source_id"],
+ kind=row["kind"],
+ source_id=row["external_id"] or "",
+ label=row["label"],
+ excerpt=row["excerpt"] or "",
+ position=int(row["position"]),
+ available=bool(row["available"]),
+ metadata=json.loads(row["metadata_json"] or "{}"),
+ created_at=float(row["created_at"]),
+ )
+ for row in rows
+ ]
+
class LearningStore:
"""Workspace-scoped transactional store for Mastery Path state."""
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index f7f906473..fa987c0b4 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -132,6 +132,78 @@ class TestListProgress:
class TestTopicProductApi:
+ def test_topic_relations_round_trip_through_create_and_reorder_edit(self, client):
+ created = client.post(
+ "/api/mastery-paths/topics",
+ json={
+ "name": "Structured route",
+ "goal": "Keep objective provenance",
+ "sources": [
+ {
+ "client_ref": "notes",
+ "kind": "notebook",
+ "label": "Study notes",
+ }
+ ],
+ "modules": [
+ {
+ "name": "Region",
+ "knowledge_points": [
+ {"client_ref": "first", "name": "First objective"},
+ {
+ "client_ref": "second",
+ "name": "Second objective",
+ "prerequisite_refs": ["first"],
+ "topic_source_refs": ["notes"],
+ },
+ ],
+ }
+ ],
+ },
+ ).json()
+ module = created["map"]["modules"][0]
+ first, second = module["knowledge_points"]
+ source_id = created["sources"][0]["id"]
+ assert second["prerequisite_ids"] == [first["id"]]
+ assert second["topic_source_ids"] == [source_id]
+
+ response = client.put(
+ f"/api/mastery-paths/topics/{created['path_id']}/map",
+ json={
+ "modules": [
+ {
+ "id": module["id"],
+ "name": "Reordered region",
+ "knowledge_points": [
+ {
+ "id": second["id"],
+ "name": "Second objective, renamed",
+ "type": second["type"],
+ "module_id": module["id"],
+ "prerequisite_ids": second["prerequisite_ids"],
+ "topic_source_ids": second["topic_source_ids"],
+ },
+ {
+ "id": first["id"],
+ "name": first["name"],
+ "type": first["type"],
+ "module_id": module["id"],
+ "prerequisite_ids": first["prerequisite_ids"],
+ "topic_source_ids": first["topic_source_ids"],
+ },
+ ],
+ }
+ ]
+ },
+ )
+
+ assert response.status_code == 200
+ edited = response.json()["map"]["modules"][0]["knowledge_points"]
+ assert [point["id"] for point in edited] == [second["id"], first["id"]]
+ assert edited[0]["name"] == "Second objective, renamed"
+ assert edited[0]["prerequisite_ids"] == [first["id"]]
+ assert edited[0]["topic_source_ids"] == [source_id]
+
def test_edit_topic_map_preserves_reordered_evidence_by_entity_id(self, client, app):
created = client.post(
"/api/mastery-paths/topics",
diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.py
index d7c671b09..06a2c293e 100644
--- a/deeptutor/learning/tests/test_mastery_tools.py
+++ b/deeptutor/learning/tests/test_mastery_tools.py
@@ -1600,6 +1600,160 @@ async def test_revise_rewrites_a_waypoint_and_resets_only_its_progress(path_id):
assert payload["knowledge_points"][0]["id"] == module["knowledge_points"][0]["id"]
+async def test_build_append_resolves_client_refs_to_final_map_ids(path_id):
+ from deeptutor.tools.mastery_tool import MasteryBuildTool
+
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ modules=[{"name": "Foundations", "knowledge_points": [{"name": "Vectors"}]}],
+ )
+
+ built = await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ mode="append",
+ modules=[
+ {
+ "name": "Products",
+ "knowledge_points": [
+ {
+ "client_ref": "dot-product",
+ "name": "Dot product",
+ "prerequisite_refs": ["test_path_m0_kp0"],
+ }
+ ],
+ }
+ ],
+ )
+
+ assert built.success, built.content
+ payload = json.loads(built.content)
+ modules = payload["map"]["modules"]
+ appended = modules[1]["knowledge_points"][0]
+ assert appended["id"] == "test_path_m1_kp0"
+ assert appended["prerequisite_ids"] == [modules[0]["knowledge_points"][0]["id"]]
+
+
+async def test_revise_rewrites_edges_across_modules(path_id):
+ from deeptutor.tools.mastery_tool import MasteryBuildTool, MasteryReviseTool
+
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ modules=[
+ {"name": "Foundations", "knowledge_points": [{"name": "Sets"}]},
+ {"name": "Relations", "knowledge_points": [{"name": "Functions"}]},
+ ],
+ )
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ mode="append",
+ modules=[
+ {
+ "name": "Applications",
+ "knowledge_points": [
+ {
+ "name": "Composition",
+ "prerequisite_refs": ["test_path_m0_kp0"],
+ }
+ ],
+ }
+ ],
+ )
+
+ revised = await MasteryReviseTool().execute(
+ _mastery_path_id=path_id,
+ module_id="test_path_m0",
+ rewrite=[{"knowledge_point_id": "test_path_m0_kp0", "name": "Sets and subsets"}],
+ )
+
+ payload = json.loads(revised.content)
+ rewritten = payload["map"]["modules"][0]["knowledge_points"][0]
+ dependent = payload["map"]["modules"][2]["knowledge_points"][0]
+ assert rewritten["id"] != "test_path_m0_kp0"
+ assert dependent["prerequisite_ids"] == [rewritten["id"]]
+
+
+async def test_revise_remove_reports_every_dependent_across_modules(path_id):
+ from deeptutor.tools.mastery_tool import MasteryBuildTool, MasteryReviseTool
+
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ modules=[
+ {"name": "Foundations", "knowledge_points": [{"name": "Sets"}]},
+ {"name": "Relations", "knowledge_points": [{"name": "Functions"}]},
+ ],
+ )
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ mode="append",
+ modules=[
+ {
+ "name": "Applications",
+ "knowledge_points": [
+ {"name": "Composition", "prerequisite_refs": ["test_path_m0_kp0"]},
+ {"name": "Inverses", "prerequisite_refs": ["test_path_m0_kp0"]},
+ ],
+ }
+ ],
+ )
+
+ refused = await MasteryReviseTool().execute(
+ _mastery_path_id=path_id,
+ module_id="test_path_m0",
+ remove=["test_path_m0_kp0"],
+ )
+
+ assert refused.success is False
+ assert "Composition" in refused.content
+ assert "Inverses" in refused.content
+ assert "Remove or change" in refused.content
+
+
+async def test_revise_relation_omission_inherits_and_empty_clears(path_id):
+ from deeptutor.tools.mastery_tool import MasteryBuildTool, MasteryReviseTool
+
+ await MasteryBuildTool().execute(
+ _mastery_path_id=path_id,
+ modules=[
+ {
+ "name": "Logic",
+ "knowledge_points": [
+ {"client_ref": "truth-tables", "name": "Truth tables"},
+ {
+ "name": "Equivalence",
+ "prerequisite_refs": ["truth-tables"],
+ },
+ ],
+ }
+ ],
+ )
+ inherited = await MasteryReviseTool().execute(
+ _mastery_path_id=path_id,
+ module_id="test_path_m0",
+ rewrite=[{"knowledge_point_id": "test_path_m0_kp1", "name": "Logical equivalence"}],
+ )
+ assert inherited.success, inherited.content
+ inherited_point = json.loads(inherited.content)["knowledge_points"][1]
+ assert inherited_point["prerequisite_ids"] == ["test_path_m0_kp0"]
+
+ cleared = await MasteryReviseTool().execute(
+ _mastery_path_id=path_id,
+ module_id="test_path_m0",
+ rewrite=[
+ {
+ "knowledge_point_id": inherited_point["id"],
+ "name": "Logical equivalence without a required prerequisite",
+ "prerequisite_ids": [],
+ }
+ ],
+ )
+ cleared_point = json.loads(cleared.content)["knowledge_points"][1]
+ assert cleared_point["prerequisite_ids"] == []
+
+
@pytest.mark.asyncio
async def test_revise_adds_and_removes_within_one_module(path_id):
from deeptutor.tools.mastery_tool import MasteryReviseTool
diff --git a/deeptutor/learning/tests/test_objective_relations.py b/deeptutor/learning/tests/test_objective_relations.py
new file mode 100644
index 000000000..818709065
--- /dev/null
+++ b/deeptutor/learning/tests/test_objective_relations.py
@@ -0,0 +1,247 @@
+"""Objective relations are structural metadata and must stay internally valid."""
+
+from __future__ import annotations
+
+from random import Random
+
+import pytest
+
+from deeptutor.learning.models import (
+ KnowledgePoint,
+ KnowledgeType,
+ LearningModule,
+ TopicMetadata,
+ TopicSource,
+ TopicSourceKind,
+)
+from deeptutor.learning.objective_relations import (
+ ObjectiveRelationError,
+ RelationRefs,
+ normalize_refs,
+ resolve_relation_refs,
+ validate_objective_relations,
+)
+from deeptutor.learning.service import LearningService
+from deeptutor.learning.storage import LearningStore
+
+
+def _kp(kp_id: str, *, prerequisites: list[str] | None = None) -> KnowledgePoint:
+ return KnowledgePoint(
+ id=kp_id,
+ name=f"Objective {kp_id}",
+ type=KnowledgeType.CONCEPT,
+ module_id="m0",
+ prerequisite_ids=prerequisites or [],
+ )
+
+
+def _module(*points: KnowledgePoint) -> LearningModule:
+ return LearningModule(id="m0", name="Foundations", order=0, knowledge_points=list(points))
+
+
+def _source(source_id: str = "source_notes", kind: TopicSourceKind = TopicSourceKind.NOTEBOOK):
+ return TopicSource(id=source_id, kind=kind, label=source_id)
+
+
+def test_legacy_objectives_default_to_empty_relations():
+ point = KnowledgePoint.model_validate(
+ {"id": "kp1", "name": "Legacy", "type": "concept", "module_id": "m0"}
+ )
+
+ assert point.prerequisite_ids == []
+ assert point.topic_source_ids == []
+
+
+def test_validation_deduplicates_and_preserves_first_reference_order():
+ point = _kp("kp1", prerequisites=["kp0", "", "kp0", "kp2"])
+ point.topic_source_ids = ["source_notes", "source_book", "source_notes"]
+
+ validate_objective_relations(
+ [_module(_kp("kp0"), point, _kp("kp2", prerequisites=["kp0"]))],
+ [_source("source_notes"), _source("source_book", TopicSourceKind.BOOK)],
+ )
+
+ assert point.prerequisite_ids == ["kp0", "kp2"]
+ assert point.topic_source_ids == ["source_notes", "source_book"]
+
+
+ "prerequisites, match",
+ [
+ (["missing"], "unknown prerequisite"),
+ (["kp1"], "own prerequisite"),
+ (["kp2"], "Prerequisite cycle"),
+ ],
+)
+def test_validation_rejects_invalid_prerequisite_edges(prerequisites: list[str], match: str):
+ first = _kp("kp1", prerequisites=prerequisites)
+ second = _kp("kp2", prerequisites=["kp1"])
+
+ with pytest.raises(ObjectiveRelationError, match=match):
+ validate_objective_relations([_module(first, second)], [])
+
+
+ "sources, match",
+ [
+ ([], "unknown or goal topic source"),
+ ([_source("goal", TopicSourceKind.GOAL)], "unknown or goal topic source"),
+ ],
+)
+def test_validation_rejects_sources_outside_the_topic(sources: list[TopicSource], match: str):
+ point = _kp("kp1")
+ point.topic_source_ids = ["goal" if not sources else "source_notes"]
+
+ with pytest.raises(ObjectiveRelationError, match=match):
+ validate_objective_relations([_module(point)], sources)
+
+
+def test_random_dags_remain_valid_until_an_invalid_edge_is_injected():
+ rng = Random(1290)
+ for _ in range(12):
+ point_ids = [f"kp{index}" for index in range(rng.randint(2, 16))]
+ points = [
+ _kp(
+ point_id,
+ prerequisites=[earlier for earlier in point_ids[:index] if rng.random() < 0.25],
+ )
+ for index, point_id in enumerate(point_ids)
+ ]
+ modules = [_module(*points)]
+ validate_objective_relations(modules, [])
+ assert all(
+ point.prerequisite_ids == normalize_refs(point.prerequisite_ids, label="prerequisite")
+ for point in points
+ )
+
+ damaged = _kp(point_ids[-1], prerequisites=[point_ids[-1]])
+ with pytest.raises(ObjectiveRelationError, match="own prerequisite"):
+ validate_objective_relations([_module(damaged)], [])
+
+
+def test_resolve_maps_client_refs_and_source_aliases_to_final_ids():
+ first = _kp("draft_a")
+ second = _kp("draft_b")
+ refs = {
+ "draft_b": RelationRefs(
+ client_ref="second",
+ prerequisite_refs=["draft_a", "draft_a"],
+ topic_source_refs=["notes"],
+ )
+ }
+
+ resolve_relation_refs(
+ [_module(first, second)],
+ refs,
+ prerequisite_aliases={"draft_a": "final_a", "second": "final_b"},
+ source_aliases={"notes": "source_notes"},
+ sources=[_source()],
+ )
+
+ assert second.prerequisite_ids == ["final_a"]
+ assert second.topic_source_ids == ["source_notes"]
+
+
+def test_append_resolves_refs_after_final_ids_are_assigned(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ metadata = TopicMetadata(path_id="topic", goal="Learn relations")
+ source = _source()
+ service.create_topic(
+ "topic",
+ name="Relations",
+ modules=[_module(_kp("base"))],
+ metadata=metadata,
+ sources=[source],
+ )
+ incoming = LearningModule(
+ id="draft_module",
+ name="Next steps",
+ order=1,
+ knowledge_points=[_kp("draft_next")],
+ )
+
+ progress = service.replace_modules_for_path(
+ "topic",
+ [incoming],
+ append=True,
+ relation_refs={
+ "draft_next": RelationRefs(
+ client_ref="next",
+ prerequisite_refs=["base"],
+ topic_source_refs=["source_notes"],
+ )
+ },
+ )
+
+ appended = progress.modules[1].knowledge_points[0]
+ assert appended.id == "topic_m1_kp0"
+ assert appended.prerequisite_ids == ["base"]
+ assert appended.topic_source_ids == ["source_notes"]
+
+
+def test_replace_build_can_start_a_fresh_objective_identity(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ first = service.replace_modules_for_path("path", [_module(_kp("kp0"))])
+ first.mastery_levels["kp0"] = 0.9
+ store.save(first)
+
+ replaced = service.replace_modules_for_path(
+ "path",
+ [_module(_kp("kp0"))],
+ fresh_identity=True,
+ )
+
+ new_id = replaced.modules[0].knowledge_points[0].id
+ assert new_id != "kp0"
+ assert new_id not in replaced.mastery_levels
+
+
+def test_fresh_replace_resolves_client_refs_without_reusing_old_ids(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ service.replace_modules_for_path("path", [_module(_kp("kp0"))])
+ replacement = _module(
+ _kp("kp0"),
+ _kp("draft", prerequisites=["new-base"]),
+ )
+
+ replaced = service.replace_modules_for_path(
+ "path",
+ [replacement],
+ fresh_identity=True,
+ relation_refs={
+ "kp0": RelationRefs(client_ref="new-base"),
+ "draft": RelationRefs(prerequisite_refs=["new-base"]),
+ },
+ )
+
+ base, dependent = replaced.modules[0].knowledge_points
+ assert base.id != "kp0"
+ assert dependent.prerequisite_ids == [base.id]
+
+
+def test_invalid_append_rolls_back_modules_and_revision(tmp_path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ seeded = service.replace_modules_for_path("topic", [_module(_kp("base"))])
+ incoming = LearningModule(
+ id="draft",
+ name="Invalid",
+ order=1,
+ knowledge_points=[_kp("draft")],
+ )
+
+ with pytest.raises(ObjectiveRelationError, match="unknown prerequisite ref"):
+ service.replace_modules_for_path(
+ "topic",
+ [incoming],
+ append=True,
+ relation_refs={"draft": RelationRefs(prerequisite_refs=["missing"])},
+ )
+
+ unchanged = store.load("topic")
+ assert unchanged is not None
+ assert unchanged.version == seeded.version
+ assert [module.id for module in unchanged.modules] == ["m0"]
diff --git a/web/components/space/learning/EditTopicRouteDialog.tsx b/web/components/space/learning/EditTopicRouteDialog.tsx
index dbd6ab246..154eaca1a 100644
--- a/web/components/space/learning/EditTopicRouteDialog.tsx
+++ b/web/components/space/learning/EditTopicRouteDialog.tsx
@@ -29,6 +29,8 @@ function topicDraft(topic: MasteryTopic): TopicDraft {
name: point.name,
type: point.type,
module_id: module.id,
+ prerequisite_ids: point.prerequisite_ids,
+ topic_source_ids: point.topic_source_ids,
})),
}),
),
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index 4e0342db5..207e04854 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -9854,9 +9854,7 @@ export interface components {
/** Goal */
readonly goal: string;
/** Modules */
- readonly modules?: readonly {
- readonly [key: string]: unknown;
- }[];
+ readonly modules?: readonly components["schemas"]["ModuleInput"][];
/** Must Cover */
readonly must_cover?: readonly string[];
/**
@@ -10450,9 +10448,7 @@ export interface components {
/** EditTopicMapRequest */
readonly EditTopicMapRequest: {
/** Modules */
- readonly modules: readonly {
- readonly [key: string]: unknown;
- }[];
+ readonly modules: readonly components["schemas"]["ModuleInput"][];
};
/** EnabledPayload */
readonly EnabledPayload: {
@@ -10744,9 +10740,7 @@ export interface components {
/** InitModulesRequest */
readonly InitModulesRequest: {
/** Modules */
- readonly modules: readonly {
- readonly [key: string]: unknown;
- }[];
+ readonly modules: readonly components["schemas"]["ModuleInput"][];
};
/** InsertBlockRequest */
readonly InsertBlockRequest: {
@@ -10867,6 +10861,38 @@ export interface components {
/** Status */
readonly status?: string | null;
};
+ /** KnowledgePointInput */
+ readonly KnowledgePointInput: {
+ /**
+ * Client Ref
+ * @default
+ */
+ readonly client_ref: string;
+ /** Id */
+ readonly id?: string | null;
+ /**
+ * Module Id
+ * @default
+ */
+ readonly module_id: string;
+ /** Name */
+ readonly name: string;
+ /** Prerequisite Ids */
+ readonly prerequisite_ids?: readonly string[];
+ /** Prerequisite Refs */
+ readonly prerequisite_refs?: readonly string[];
+ /** Topic Source Ids */
+ readonly topic_source_ids?: readonly string[];
+ /** Topic Source Refs */
+ readonly topic_source_refs?: readonly string[];
+ /** @default concept */
+ readonly type: components["schemas"]["KnowledgeType"];
+ };
+ /**
+ * KnowledgeType
+ * @enum {string}
+ */
+ readonly KnowledgeType: "memory" | "concept" | "procedure" | "design";
/** LanguageUpdate */
readonly LanguageUpdate: {
/**
@@ -11481,6 +11507,27 @@ export interface components {
*/
readonly model: string;
};
+ /** ModuleInput */
+ readonly ModuleInput: {
+ /** Id */
+ readonly id?: string | null;
+ /** Knowledge Points */
+ readonly knowledge_points?: readonly components["schemas"]["KnowledgePointInput"][];
+ /** Name */
+ readonly name: string;
+ /**
+ * Objective
+ * @default
+ */
+ readonly objective: string;
+ /** Order */
+ readonly order?: number | null;
+ /**
+ * Pass Threshold
+ * @default 0.7
+ */
+ readonly pass_threshold: number;
+ };
/** MoveBlockRequest */
readonly MoveBlockRequest: {
/** Block Id */
@@ -12772,6 +12819,11 @@ export interface components {
* @default true
*/
readonly available: boolean;
+ /**
+ * Client Ref
+ * @default
+ */
+ readonly client_ref: string;
/**
* Excerpt
* @default
@@ -13782,6 +13834,9 @@ export type SchemaInvidiousSettings =
components["schemas"]["InvidiousSettings"];
export type SchemaKnowledgeBaseInfo =
components["schemas"]["KnowledgeBaseInfo"];
+export type SchemaKnowledgePointInput =
+ components["schemas"]["KnowledgePointInput"];
+export type SchemaKnowledgeType = components["schemas"]["KnowledgeType"];
export type SchemaLanguageUpdate = components["schemas"]["LanguageUpdate"];
export type SchemaLearnerOverrideRequest =
components["schemas"]["LearnerOverrideRequest"];
@@ -13822,6 +13877,7 @@ export type SchemaMinerUSettingsUpdate =
components["schemas"]["MinerUSettingsUpdate"];
export type SchemaModelCapabilitiesQuery =
components["schemas"]["ModelCapabilitiesQuery"];
+export type SchemaModuleInput = components["schemas"]["ModuleInput"];
export type SchemaMoveBlockRequest = components["schemas"]["MoveBlockRequest"];
export type SchemaMoveFilePayload = components["schemas"]["MoveFilePayload"];
export type SchemaMoveRecordRequest =
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index 9c2862f3e..4e8a49de0 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -1793,8 +1793,7 @@
},
"modules": {
"items": {
- "additionalProperties": true,
- "type": "object"
+ "$ref": "#/components/schemas/ModuleInput"
},
"maxItems": 20,
"title": "Modules",
@@ -3074,8 +3073,7 @@
"properties": {
"modules": {
"items": {
- "additionalProperties": true,
- "type": "object"
+ "$ref": "#/components/schemas/ModuleInput"
},
"maxItems": 20,
"minItems": 1,
@@ -3817,8 +3815,7 @@
"properties": {
"modules": {
"items": {
- "additionalProperties": true,
- "type": "object"
+ "$ref": "#/components/schemas/ModuleInput"
},
"title": "Modules",
"type": "array"
@@ -4085,6 +4082,84 @@
"title": "KnowledgeBaseInfo",
"type": "object"
},
+ "KnowledgePointInput": {
+ "properties": {
+ "client_ref": {
+ "default": "",
+ "title": "Client Ref",
+ "type": "string"
+ },
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Id"
+ },
+ "module_id": {
+ "default": "",
+ "title": "Module Id",
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 200,
+ "minLength": 1,
+ "title": "Name",
+ "type": "string"
+ },
+ "prerequisite_ids": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Prerequisite Ids",
+ "type": "array"
+ },
+ "prerequisite_refs": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Prerequisite Refs",
+ "type": "array"
+ },
+ "topic_source_ids": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Topic Source Ids",
+ "type": "array"
+ },
+ "topic_source_refs": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Topic Source Refs",
+ "type": "array"
+ },
+ "type": {
+ "$ref": "#/components/schemas/KnowledgeType",
+ "default": "concept"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "KnowledgePointInput",
+ "type": "object"
+ },
+ "KnowledgeType": {
+ "enum": [
+ "memory",
+ "concept",
+ "procedure",
+ "design"
+ ],
+ "title": "KnowledgeType",
+ "type": "string"
+ },
"LLMSelection": {
"additionalProperties": false,
"properties": {
@@ -5266,6 +5341,61 @@
"title": "ModelCapabilitiesQuery",
"type": "object"
},
+ "ModuleInput": {
+ "properties": {
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Id"
+ },
+ "knowledge_points": {
+ "items": {
+ "$ref": "#/components/schemas/KnowledgePointInput"
+ },
+ "title": "Knowledge Points",
+ "type": "array"
+ },
+ "name": {
+ "maxLength": 200,
+ "minLength": 1,
+ "title": "Name",
+ "type": "string"
+ },
+ "objective": {
+ "default": "",
+ "maxLength": 300,
+ "title": "Objective",
+ "type": "string"
+ },
+ "order": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Order"
+ },
+ "pass_threshold": {
+ "default": 0.7,
+ "title": "Pass Threshold",
+ "type": "number"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "ModuleInput",
+ "type": "object"
+ },
"MoveBlockRequest": {
"properties": {
"block_id": {
@@ -8064,6 +8194,11 @@
"title": "Available",
"type": "boolean"
},
+ "client_ref": {
+ "default": "",
+ "title": "Client Ref",
+ "type": "string"
+ },
"excerpt": {
"default": "",
"maxLength": 8000,
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 558254a46..ced1e6fb0 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -7,9 +7,14 @@ export interface ModuleInit {
pass_threshold?: number;
knowledge_points: {
id: string;
+ client_ref?: string;
name: string;
type: string;
module_id: string;
+ prerequisite_ids?: string[];
+ prerequisite_refs?: string[];
+ topic_source_ids?: string[];
+ topic_source_refs?: string[];
}[];
}
@@ -64,6 +69,8 @@ export interface MapKnowledgePoint {
id: string;
name: string;
type: string;
+ prerequisite_ids: string[];
+ topic_source_ids: string[];
status: ObjectiveStatus;
mastery: number;
mastery_source: "system" | "learner" | "";
@@ -399,6 +406,7 @@ export interface TopicSource {
export interface TopicSourceInput {
id?: string;
+ client_ref?: string;
kind: TopicSourceKind;
source_id?: string;
label: string;