asnannp commited on
Commit
ab01cae
·
1 Parent(s): 65d68f5

deploy: sync backend to Space root (learn-lesson HF cache fix)

Browse files
app/schemas/learning_state.py CHANGED
@@ -554,10 +554,10 @@ class CheckpointRequest(BaseModel):
554
  ]
555
  question_id: str = Field(min_length=1, max_length=120)
556
  question_type: Literal["mcq", "short", "numerical", "diagram", "board"]
557
- prompt: str = Field(min_length=1, max_length=2000)
558
  student_answer: str = Field(max_length=4000)
559
- correct_answer: str = Field(min_length=1, max_length=4000)
560
- client_correct: bool
561
  attempt_index: int = Field(default=1, ge=1, le=10)
562
  hint_used: bool = False
563
  expected_keywords: list[str] = Field(default_factory=list, max_length=40)
 
554
  ]
555
  question_id: str = Field(min_length=1, max_length=120)
556
  question_type: Literal["mcq", "short", "numerical", "diagram", "board"]
557
+ prompt: str = Field(default="", max_length=2000, json_schema_extra={"deprecated": True})
558
  student_answer: str = Field(max_length=4000)
559
+ correct_answer: str = Field(default="", max_length=4000, json_schema_extra={"deprecated": True})
560
+ client_correct: bool = Field(default=False, json_schema_extra={"deprecated": True})
561
  attempt_index: int = Field(default=1, ge=1, le=10)
562
  hint_used: bool = False
563
  expected_keywords: list[str] = Field(default_factory=list, max_length=40)
app/services/adaptive_engine.py CHANGED
@@ -23,6 +23,7 @@ from app.models.learning_state import (
23
  RepairItem,
24
  RevisionItem,
25
  StudentProfileState,
 
26
  TopicMastery,
27
  UsageEvent,
28
  )
@@ -56,6 +57,7 @@ from app.services.mastery_engine import (
56
  )
57
  from app.services.today_plan_service import refresh_daily_plan_totals, replan_today
58
  from app.services.planning_context import aware
 
59
 
60
 
61
  REPAIR_TASK_MINUTES = 10
@@ -79,8 +81,17 @@ def _owned_chapter_for_checkpoint(
79
  Chapter.user_id == user_id,
80
  )
81
  )
82
- if chapter is not None:
83
- return chapter
 
 
 
 
 
 
 
 
 
84
  return db.scalar(
85
  select(Chapter).where(
86
  Chapter.user_id == user_id,
@@ -203,18 +214,6 @@ def repair_item_out(item: RepairItem) -> RepairItemOut:
203
  )
204
 
205
 
206
- def _server_verified_correct(payload: CheckpointRequest) -> bool:
207
- """Recompute correctness where the server can do so deterministically.
208
-
209
- MCQ answers are verifiable by comparison; free-text answers use the client's
210
- deterministic rubric result (also recorded verbatim in the event payload for
211
- audit). The server never silently trusts a claim it can cheaply verify.
212
- """
213
- if payload.question_type == "mcq":
214
- return payload.student_answer.strip().casefold() == payload.correct_answer.strip().casefold()
215
- return payload.client_correct
216
-
217
-
218
  def _open_repairs_for_concept(db: Session, user_id: str, concept_key: str) -> list[RepairItem]:
219
  return list(
220
  db.scalars(
@@ -297,6 +296,7 @@ def record_checkpoint(
297
  payload: CheckpointRequest,
298
  now: datetime | None = None,
299
  planning_now: datetime | None = None,
 
300
  ) -> CheckpointConsequenceResponse:
301
  # Idempotency: a replayed client_event_id returns the stored consequence.
302
  existing = db.scalar(
@@ -306,13 +306,37 @@ def record_checkpoint(
306
  )
307
  )
308
  if existing is not None:
 
 
 
 
 
 
309
  stored = dict(existing.consequence or {})
310
  stored["replayed"] = True
311
  return CheckpointConsequenceResponse.model_validate(stored)
312
 
313
  now = aware(now) or _now()
314
  plan_clock = aware(planning_now) or now
315
- correct = _server_verified_correct(payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
  error_category: str | None = None
318
  if not correct:
@@ -336,14 +360,7 @@ def record_checkpoint(
336
  # A correction to an already-seen question is practice, not proof of
337
  # transfer. Use persisted attempts rather than the bounded mastery log
338
  # so restarting the class cannot disguise a retry as a fresh check.
339
- previous_question = db.scalar(
340
- select(CheckpointEvent.id).where(
341
- CheckpointEvent.user_id == user_id,
342
- CheckpointEvent.concept_key == payload.concept_key,
343
- CheckpointEvent.question_id == payload.question_id,
344
- ).limit(1)
345
- )
346
- independent_repair_check = previous_question is None
347
  if correct and open_repairs:
348
  logger.debug(
349
  "[FIX:independent-repair] checked recovery evidence",
@@ -425,6 +442,10 @@ def record_checkpoint(
425
  next_review_at=mastery_row.next_review_at if mastery_row else None,
426
  evidence=dict(mastery_row.evidence or {}) if mastery_row else {},
427
  )
 
 
 
 
428
  # Capture the BEFORE base/overlay for mastery transition instrumentation
429
  # (M7). An overlay clearing is logged separately and must never count as
430
  # a base mastery gain.
@@ -536,9 +557,11 @@ def record_checkpoint(
536
  payload={
537
  "question_type": payload.question_type,
538
  "prompt": payload.prompt[:1000],
539
- "student_answer": payload.student_answer[:1000],
540
  "correct_answer": payload.correct_answer[:1000],
541
  "client_correct": payload.client_correct,
 
 
542
  "expected_keywords": payload.expected_keywords,
543
  "time_spent_seconds": payload.time_spent_seconds,
544
  "difficulty": payload.difficulty,
@@ -565,6 +588,11 @@ def record_checkpoint(
565
  )
566
  if winner is None:
567
  raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Checkpoint conflict; retry.")
 
 
 
 
 
568
  stored = dict(winner.consequence or {})
569
  stored["replayed"] = True
570
  return CheckpointConsequenceResponse.model_validate(stored)
 
23
  RepairItem,
24
  RevisionItem,
25
  StudentProfileState,
26
+ Subject,
27
  TopicMastery,
28
  UsageEvent,
29
  )
 
57
  )
58
  from app.services.today_plan_service import refresh_daily_plan_totals, replan_today
59
  from app.services.planning_context import aware
60
+ from app.services.checkpoint_evaluation import EVALUATION_VERSION, evaluate_checkpoint
61
 
62
 
63
  REPAIR_TASK_MINUTES = 10
 
81
  Chapter.user_id == user_id,
82
  )
83
  )
84
+ if chapter is None:
85
+ raise HTTPException(404, detail="Chapter not found.")
86
+ if chapter.catalog_id != payload.chapter_catalog_id:
87
+ raise HTTPException(422, detail="Checkpoint chapter does not match its published question.")
88
+ if payload.subject_id and payload.subject_id != chapter.subject_id:
89
+ raise HTTPException(422, detail="Checkpoint subject does not match its chapter.")
90
+ return chapter
91
+ if payload.subject_id and db.scalar(select(Subject.id).where(
92
+ Subject.id == payload.subject_id, Subject.user_id == user_id,
93
+ )) is None:
94
+ raise HTTPException(404, detail="Subject not found.")
95
  return db.scalar(
96
  select(Chapter).where(
97
  Chapter.user_id == user_id,
 
214
  )
215
 
216
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  def _open_repairs_for_concept(db: Session, user_id: str, concept_key: str) -> list[RepairItem]:
218
  return list(
219
  db.scalars(
 
296
  payload: CheckpointRequest,
297
  now: datetime | None = None,
298
  planning_now: datetime | None = None,
299
+ trusted_correct: bool | None = None,
300
  ) -> CheckpointConsequenceResponse:
301
  # Idempotency: a replayed client_event_id returns the stored consequence.
302
  existing = db.scalar(
 
306
  )
307
  )
308
  if existing is not None:
309
+ source_id = dict(existing.payload or {}).get("source_question_id")
310
+ if (existing.concept_key != payload.concept_key
311
+ or payload.question_id not in {existing.question_id, source_id}
312
+ or dict(existing.payload or {}).get("student_answer") != payload.student_answer):
313
+ raise HTTPException(409, detail={"code": "CHECKPOINT_REPLAY_MISMATCH",
314
+ "message": "This saved attempt belongs to a different answer. Start a new attempt."})
315
  stored = dict(existing.consequence or {})
316
  stored["replayed"] = True
317
  return CheckpointConsequenceResponse.model_validate(stored)
318
 
319
  now = aware(now) or _now()
320
  plan_clock = aware(planning_now) or now
321
+ source_question_id = payload.question_id
322
+ authored_source_id = source_question_id
323
+ if trusted_correct is None:
324
+ payload, correct, authored_source_id = evaluate_checkpoint(payload)
325
+ else:
326
+ # Private Python-only path for the server-owned written rubric. The
327
+ # HTTP schema forbids this field; browser flags can never reach it.
328
+ correct = trusted_correct
329
+ # Canonicalization must not make a pre-release raw question ID look fresh.
330
+ # Treat durable attempts conservatively, including previously client-graded
331
+ # records: they can establish familiarity, never manufacture new success.
332
+ question_aliases = {payload.question_id, source_question_id, authored_source_id}
333
+ if trusted_correct is None:
334
+ question_aliases.add(payload.question_id.rsplit(":", 1)[-1])
335
+ previous_attempts = list(db.scalars(select(CheckpointEvent).where(
336
+ CheckpointEvent.user_id == user_id,
337
+ CheckpointEvent.concept_key == payload.concept_key,
338
+ CheckpointEvent.question_id.in_(question_aliases),
339
+ )))
340
 
341
  error_category: str | None = None
342
  if not correct:
 
360
  # A correction to an already-seen question is practice, not proof of
361
  # transfer. Use persisted attempts rather than the bounded mastery log
362
  # so restarting the class cannot disguise a retry as a fresh check.
363
+ independent_repair_check = not previous_attempts
 
 
 
 
 
 
 
364
  if correct and open_repairs:
365
  logger.debug(
366
  "[FIX:independent-repair] checked recovery evidence",
 
442
  next_review_at=mastery_row.next_review_at if mastery_row else None,
443
  evidence=dict(mastery_row.evidence or {}) if mastery_row else {},
444
  )
445
+ if any(attempt.correct for attempt in previous_attempts):
446
+ seen = list(snapshot.evidence.get("seen_question_correct") or [])
447
+ if payload.question_id not in seen:
448
+ snapshot.evidence["seen_question_correct"] = [*seen, payload.question_id]
449
  # Capture the BEFORE base/overlay for mastery transition instrumentation
450
  # (M7). An overlay clearing is logged separately and must never count as
451
  # a base mastery gain.
 
557
  payload={
558
  "question_type": payload.question_type,
559
  "prompt": payload.prompt[:1000],
560
+ "student_answer": payload.student_answer,
561
  "correct_answer": payload.correct_answer[:1000],
562
  "client_correct": payload.client_correct,
563
+ "source_question_id": source_question_id,
564
+ "evaluation_version": EVALUATION_VERSION if trusted_correct is None else "server-written-rubric",
565
  "expected_keywords": payload.expected_keywords,
566
  "time_spent_seconds": payload.time_spent_seconds,
567
  "difficulty": payload.difficulty,
 
588
  )
589
  if winner is None:
590
  raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Checkpoint conflict; retry.")
591
+ if (winner.concept_key != payload.concept_key
592
+ or winner.question_id not in question_aliases
593
+ or dict(winner.payload or {}).get("student_answer") != payload.student_answer):
594
+ raise HTTPException(409, detail={"code": "CHECKPOINT_REPLAY_MISMATCH",
595
+ "message": "This saved attempt belongs to a different answer. Start a new attempt."})
596
  stored = dict(winner.consequence or {})
597
  stored["replayed"] = True
598
  return CheckpointConsequenceResponse.model_validate(stored)
app/services/checkpoint_evaluation.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resolve published prompts before accepting checkpoint mastery evidence.
2
+
3
+ Browser answer keys and correctness flags are compatibility fields, never
4
+ grading authority. Written class answers use their separate private rubric.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import math
10
+ import re
11
+
12
+ from fastapi import HTTPException
13
+
14
+ from app.schemas.learning_state import CheckpointRequest
15
+ from app.services.content_manifest import load_content_manifest
16
+ from app.services.rubric_evaluation import _canonical_unit, _has_keyword, _normalise
17
+ from app.services.tuition_content_contract import load_tuition_content_contract
18
+
19
+ logger = logging.getLogger(__name__)
20
+ EVALUATION_VERSION = "authored-checkpoint-v1"
21
+ _FUNCTION_WORDS = frozenset("a an the is are of in on to from and or for with by at it its that this be as one".split())
22
+
23
+
24
+ def _keywords(answer: str) -> list[str]:
25
+ return list(dict.fromkeys(token for token in _normalise(answer).split()
26
+ if token not in _FUNCTION_WORDS))
27
+
28
+
29
+ def _numeric_result(answer: str) -> tuple[float, str | None] | None:
30
+ # Grade the final authored value, not ANY number in its working (givens
31
+ # and intermediate values are not correct final answers).
32
+ value = re.sub(r"(?:\(|;)\s*(?:real|virtual|convex|concave|inverted|upright|erect)\b.*$", "", answer, flags=re.I)
33
+ match = re.search(r"([-+]?\d+(?:\.\d+)?)\s*([a-z]+(?:/[a-z]+)?)?\s*$", _normalise(value).rstrip("."))
34
+ if match is None:
35
+ return None
36
+ number, unit = float(match.group(1)), _canonical_unit(match.group(2))
37
+ # Reviewed SI conversions; only the final value/unit pair is converted.
38
+ conversions = {"cm": (0.01, "m"), "mm": (0.001, "m"), "km": (1000, "m"),
39
+ "khz": (1000, "hz"), "mhz": (1_000_000, "hz")}
40
+ if unit in conversions:
41
+ factor, unit = conversions[unit]
42
+ number *= factor
43
+ return number, unit
44
+
45
+
46
+ def _grade(*, answer: str, expected: str, question_type: str,
47
+ required_keywords: list[str] | None = None) -> bool:
48
+ normalized = _normalise(answer)
49
+ if not normalized:
50
+ return False
51
+ if question_type == "mcq":
52
+ return normalized == _normalise(expected)
53
+ # A negated assertion must not pass by containing the right keywords.
54
+ if re.search(r"\b(?:not|never|incorrect|false)\b", normalized) and not re.search(
55
+ r"\b(?:not|never|incorrect|false)\b", _normalise(expected)
56
+ ):
57
+ return False
58
+ if question_type == "numerical":
59
+ result = _numeric_result(expected)
60
+ submitted = _numeric_result(answer)
61
+ return bool(result and submitted
62
+ and math.isclose(submitted[0], result[0], rel_tol=1e-6, abs_tol=1e-6)
63
+ and submitted[1] == result[1])
64
+ # Authored short recall has no board-mark rubric. Require the whole
65
+ # source-backed idea, not one matching word; reviewed equivalents allow
66
+ # reordered natural wording. This does not claim subjective exam grading.
67
+ # Explicit source-authored scoring points can distinguish the definition
68
+ # from optional annotations (e.g. frequency's definition vs its SI unit).
69
+ # These come ONLY from the published registry, never from browser input.
70
+ keywords = required_keywords or _keywords(expected)
71
+ return bool(keywords) and all(_has_keyword(normalized, keyword) for keyword in keywords)
72
+
73
+
74
+ def evaluate_checkpoint(payload: CheckpointRequest) -> tuple[CheckpointRequest, bool, str]:
75
+ contract = load_tuition_content_contract()
76
+ manifest = load_content_manifest()
77
+ expected_concept = f"{payload.chapter_catalog_id}:{payload.mission_id}"
78
+ if payload.concept_key != expected_concept:
79
+ raise HTTPException(422, detail={"code": "CHECKPOINT_CONCEPT_MISMATCH",
80
+ "message": "This question belongs to a different concept."})
81
+ matches = []
82
+ for lesson in contract.lessons:
83
+ if lesson.chapter_id != payload.chapter_catalog_id or not lesson.is_teachable:
84
+ continue
85
+ source_mission = manifest.mission(lesson.chapter_id, lesson.mission_id)
86
+ if source_mission is None or not source_mission.assignable:
87
+ continue
88
+ for question in lesson.checkpoints:
89
+ if (question.get("conceptMissionId") == payload.mission_id
90
+ and payload.question_id in {question.get("id"), question.get("sourceQuestionId")}):
91
+ matches.append(question)
92
+ # Identical duplicates in class views share ONE evidence identity. An
93
+ # ambiguous or unknown published answer must not become student evidence.
94
+ if not matches or any(question != matches[0] for question in matches[1:]):
95
+ logger.debug("[FIX:checkpoint-authority] rejected unregistered or ambiguous prompt")
96
+ raise HTTPException(422, detail={"code": "CHECKPOINT_QUESTION_UNAVAILABLE",
97
+ "message": "This checkpoint needs reviewed question content. Reload the class."})
98
+ question = matches[0]
99
+ question_type = str(question["type"])
100
+ expected = str(question["answer"])
101
+ keywords = question.get("requiredKeywords") or _keywords(expected)
102
+ correct = _grade(answer=payload.student_answer, expected=expected,
103
+ question_type=question_type, required_keywords=keywords)
104
+ resolved = payload.model_copy(update={
105
+ "question_id": str(question["id"]),
106
+ "question_type": question_type,
107
+ "kind": question["kind"],
108
+ "prompt": str(question["prompt"]),
109
+ "correct_answer": expected,
110
+ "client_correct": correct,
111
+ "concept_label": question["conceptLabel"],
112
+ "difficulty": question["difficulty"],
113
+ "skill_tags": [],
114
+ "expected_keywords": keywords,
115
+ })
116
+ logger.debug("[FIX:checkpoint-authority] evaluated published checkpoint type=%s correct=%s", question_type, correct)
117
+ return resolved, correct, str(question["sourceQuestionId"])
app/services/tuition_content_contract.py CHANGED
@@ -40,6 +40,7 @@ class TuitionLessonContract:
40
  quiz: tuple[dict[str, Any], ...]
41
  pyq_evidence_status: str
42
  content_fingerprint: str
 
43
 
44
  @property
45
  def is_teachable(self) -> bool:
@@ -162,6 +163,7 @@ def load_tuition_content_contract() -> TuitionContentContract:
162
  quiz=quiz,
163
  pyq_evidence_status=_required_string(item.get("pyqEvidenceStatus"), "PYQ evidence status"),
164
  content_fingerprint=_required_string(item.get("contentFingerprint"), "content fingerprint"),
 
165
  )
166
  findings = validate_lesson_contract(
167
  lesson,
 
40
  quiz: tuple[dict[str, Any], ...]
41
  pyq_evidence_status: str
42
  content_fingerprint: str
43
+ checkpoints: tuple[dict[str, Any], ...] = ()
44
 
45
  @property
46
  def is_teachable(self) -> bool:
 
163
  quiz=quiz,
164
  pyq_evidence_status=_required_string(item.get("pyqEvidenceStatus"), "PYQ evidence status"),
165
  content_fingerprint=_required_string(item.get("contentFingerprint"), "content fingerprint"),
166
+ checkpoints=tuple(item.get("checkpoints") or []),
167
  )
168
  findings = validate_lesson_contract(
169
  lesson,
app/services/tuition_session_service.py CHANGED
@@ -499,6 +499,7 @@ def submit_tuition_written_attempt(
499
  current = aware(now) or _now()
500
  consequence = record_checkpoint(
501
  db,
 
502
  user_id=user_id,
503
  payload=CheckpointRequest(
504
  client_event_id=payload.client_attempt_id,
 
499
  current = aware(now) or _now()
500
  consequence = record_checkpoint(
501
  db,
502
+ trusted_correct=correction.awarded_marks >= correction.max_marks,
503
  user_id=user_id,
504
  payload=CheckpointRequest(
505
  client_event_id=payload.client_attempt_id,
app/services/tuition_written_evidence.py CHANGED
@@ -1,13 +1,17 @@
1
  """Locate authored written evidence without confusing a prompt with a session."""
2
  from __future__ import annotations
3
 
4
- from sqlalchemy import select
 
 
5
  from sqlalchemy.orm import Session
6
 
7
  from app.models.class_session_progress import ClassSessionProgress
8
  from app.models.learning_state import CheckpointEvent
9
  from app.services.tuition_content_contract import load_tuition_content_contract
10
 
 
 
11
 
12
  def written_event_for_session(db: Session, *, record: ClassSessionProgress) -> CheckpointEvent | None:
13
  lesson = load_tuition_content_contract().lesson(record.chapter_catalog_id, record.mission_id)
@@ -23,7 +27,11 @@ def written_event_for_session(db: Session, *, record: ClassSessionProgress) -> C
23
  state = dict(record.data or {}).get("phase5")
24
  attempt_id = state.get("written_attempt_id") if isinstance(state, dict) else None
25
  if attempt_id:
26
- query = query.where(CheckpointEvent.client_event_id == attempt_id)
 
 
 
 
27
  for event in db.scalars(query.order_by(CheckpointEvent.created_at.desc())):
28
  provenance = dict(event.payload or {})
29
  # These fields are added by the authored correction service, not by the
@@ -32,5 +40,7 @@ def written_event_for_session(db: Session, *, record: ClassSessionProgress) -> C
32
  if (provenance.get("tuition_session_id") == record.class_session_id
33
  and provenance.get("content_fingerprint") == record.content_fingerprint
34
  and isinstance(provenance.get("correction"), dict)):
 
 
35
  return event
36
  return None
 
1
  """Locate authored written evidence without confusing a prompt with a session."""
2
  from __future__ import annotations
3
 
4
+ import logging
5
+
6
+ from sqlalchemy import or_, select
7
  from sqlalchemy.orm import Session
8
 
9
  from app.models.class_session_progress import ClassSessionProgress
10
  from app.models.learning_state import CheckpointEvent
11
  from app.services.tuition_content_contract import load_tuition_content_contract
12
 
13
+ logger = logging.getLogger(__name__)
14
+
15
 
16
  def written_event_for_session(db: Session, *, record: ClassSessionProgress) -> CheckpointEvent | None:
17
  lesson = load_tuition_content_contract().lesson(record.chapter_catalog_id, record.mission_id)
 
27
  state = dict(record.data or {}).get("phase5")
28
  attempt_id = state.get("written_attempt_id") if isinstance(state, dict) else None
29
  if attempt_id:
30
+ # Older browser drafts saved checkpoint_id here instead of the client
31
+ # attempt ID. Accept either durable identity, but retain all ownership,
32
+ # concept, session provenance and content-fingerprint checks below.
33
+ query = query.where(or_(CheckpointEvent.client_event_id == attempt_id,
34
+ CheckpointEvent.id == attempt_id))
35
  for event in db.scalars(query.order_by(CheckpointEvent.created_at.desc())):
36
  provenance = dict(event.payload or {})
37
  # These fields are added by the authored correction service, not by the
 
40
  if (provenance.get("tuition_session_id") == record.class_session_id
41
  and provenance.get("content_fingerprint") == record.content_fingerprint
42
  and isinstance(provenance.get("correction"), dict)):
43
+ logger.debug("[FIX:written-evidence-identity] resolved saved written evidence legacy_id=%s",
44
+ bool(attempt_id and attempt_id == event.id))
45
  return event
46
  return None
scripts/generate-tuition-content-contract.ts CHANGED
@@ -3,6 +3,8 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
  import { dirname, resolve } from "node:path";
4
  import { getAllLessonSeeds } from "../src/lib/teaching/physicsLessonSeeds";
5
  import { objectivesForLessonSeed } from "../src/lib/teaching/lessonObjectives";
 
 
6
  import {
7
  CONTENT_VERSION,
8
  LEGACY_CHEM_SEED_OVERRIDE_IDS,
@@ -20,6 +22,41 @@ const manifestPath = resolve(root, "shared", "content-manifest.json");
20
  const outputPath = resolve(root, "shared", "tuition-content-contract.json");
21
  const REQUIRED_STEPS = ["teach", "your-turn", "correction", "quiz", "save-revision"];
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  type ManifestChapter = {
24
  chapterId: string;
25
  subject: string;
@@ -36,7 +73,7 @@ async function main() {
36
  const lessons: Array<Record<string, unknown>> = [];
37
  const seen = new Set<string>();
38
 
39
- const pushLesson = (payload: Record<string, unknown>) => {
40
  const chapterId = String(payload.chapterId);
41
  const missionId = String(payload.missionId);
42
  const key = `${chapterId}|${missionId}`;
@@ -45,6 +82,10 @@ async function main() {
45
  lessons.push({
46
  ...payload,
47
  contentFingerprint: createHash("sha256").update(JSON.stringify(payload)).digest("hex"),
 
 
 
 
48
  });
49
  };
50
 
@@ -103,7 +144,7 @@ async function main() {
103
  objectiveIds: [objectives[Math.min(index, objectives.length - 1)]?.id].filter(Boolean),
104
  })),
105
  pyqEvidenceStatus: seed.pyqEvidenceStatus,
106
- });
107
  }
108
 
109
  for (const { coverage, pack } of listReadyPackChapters()) {
@@ -122,6 +163,7 @@ async function main() {
122
  chapterTitle,
123
  missionTitle,
124
  }),
 
125
  );
126
  }
127
 
 
3
  import { dirname, resolve } from "node:path";
4
  import { getAllLessonSeeds } from "../src/lib/teaching/physicsLessonSeeds";
5
  import { objectivesForLessonSeed } from "../src/lib/teaching/lessonObjectives";
6
+ import { classSessionFromSeed, classSessionFromStudyPack, type TuitionClassSession } from "../src/components/tuition/chapter-dashboard/classSessionData";
7
+ import { transferQuestionFor } from "../src/components/tuition/class/adaptiveCheckpoint";
8
  import {
9
  CONTENT_VERSION,
10
  LEGACY_CHEM_SEED_OVERRIDE_IDS,
 
22
  const outputPath = resolve(root, "shared", "tuition-content-contract.json");
23
  const REQUIRED_STEPS = ["teach", "your-turn", "correction", "quiz", "save-revision"];
24
 
25
+ function checkpointContract(session: TuitionClassSession | null) {
26
+ if (!session || session.notCurated) return [];
27
+ const checkpoints: Array<Record<string, unknown>> = [];
28
+ session.quiz.questions.forEach((question, index) => {
29
+ const conceptMissionId = question.conceptMissionId ?? session.missionId;
30
+ // Exam-style is a display category, not proof of numerical content.
31
+ // Dates, chemical equations and theory answers containing digits must not
32
+ // receive numerical evidence or be graded as a single final number.
33
+ const numerical = question.type === "exam-style"
34
+ && ["Physics", "Maths", "Mathematics"].includes(session.subject)
35
+ && /(?:=|\bis\b|^|\s)[-+−]?\d+(?:\.\d+)?\s*(?:[a-zA-Z]+(?:\/[a-zA-Z]+)?)?(?:\s*[.(;].*)?$/.test(question.answer);
36
+ const type = question.options?.length ? "mcq" : numerical ? "numerical" : "short";
37
+ checkpoints.push({
38
+ id: `${session.chapterId}:${conceptMissionId}:${question.id.startsWith(session.chapterId)
39
+ ? question.id.slice(session.chapterId.length).replace(/^[-:]/, "") : question.id}`,
40
+ sourceQuestionId: question.id,
41
+ conceptMissionId,
42
+ conceptLabel: question.conceptLabel ?? session.missionTitle,
43
+ prompt: question.prompt,
44
+ answer: question.answer,
45
+ options: question.options ?? [],
46
+ type,
47
+ kind: `checkpoint_${type}`,
48
+ difficulty: question.difficulty ?? "medium",
49
+ });
50
+ const transfer = transferQuestionFor(session, index);
51
+ if (transfer && !checkpoints.some((item) => item.id === transfer.id)) {
52
+ checkpoints.push({ ...transfer, sourceQuestionId: transfer.id, conceptMissionId,
53
+ conceptLabel: question.conceptLabel ?? session.missionTitle, options: [],
54
+ type: "short", kind: "transfer_check", difficulty: "medium" });
55
+ }
56
+ });
57
+ return checkpoints;
58
+ }
59
+
60
  type ManifestChapter = {
61
  chapterId: string;
62
  subject: string;
 
73
  const lessons: Array<Record<string, unknown>> = [];
74
  const seen = new Set<string>();
75
 
76
+ const pushLesson = (payload: Record<string, unknown>, session: TuitionClassSession | null) => {
77
  const chapterId = String(payload.chapterId);
78
  const missionId = String(payload.missionId);
79
  const key = `${chapterId}|${missionId}`;
 
82
  lessons.push({
83
  ...payload,
84
  contentFingerprint: createHash("sha256").update(JSON.stringify(payload)).digest("hex"),
85
+ // Keep the established written/session fingerprint intact. Checkpoint
86
+ // grading has its own additive, independently versioned contract.
87
+ checkpointVersion: "authored-checkpoint-v1",
88
+ checkpoints: checkpointContract(session),
89
  });
90
  };
91
 
 
144
  objectiveIds: [objectives[Math.min(index, objectives.length - 1)]?.id].filter(Boolean),
145
  })),
146
  pyqEvidenceStatus: seed.pyqEvidenceStatus,
147
+ }, classSessionFromSeed(seed));
148
  }
149
 
150
  for (const { coverage, pack } of listReadyPackChapters()) {
 
163
  chapterTitle,
164
  missionTitle,
165
  }),
166
+ classSessionFromStudyPack(coverage.chapterId),
167
  );
168
  }
169
 
shared/tuition-content-contract.json CHANGED
The diff for this file is too large to render. See raw diff
 
src/components/tuition/class/AdaptiveQuizStep.tsx CHANGED
@@ -16,10 +16,7 @@ import {
16
  checkpointQuestionType,
17
  firstOpenQuestionIndex,
18
  freshQuestionState,
19
- isCheckpointAnswerCorrect,
20
- isTransferAnswerCorrect,
21
  minimalHintFor,
22
- significantAnswerTokens,
23
  transferQuestionFor,
24
  type AdaptiveCheckpointState,
25
  } from "./adaptiveCheckpoint";
@@ -153,7 +150,6 @@ export function AdaptiveQuizStep({
153
  }
154
  setSubmitting(true);
155
  setSyncError(null);
156
- const clientCorrect = isCheckpointAnswerCorrect(question, selected);
157
  try {
158
  const context = await resolveContext();
159
  const consequence = await recordLearningCheckpoint({
@@ -165,13 +161,9 @@ export function AdaptiveQuizStep({
165
  kind: checkpointKindFor(question),
166
  question_id: question.id,
167
  question_type: checkpointQuestionType(question),
168
- prompt: question.prompt,
169
  student_answer: selected,
170
- correct_answer: question.answer,
171
- client_correct: clientCorrect,
172
  attempt_index: questionState.attempt,
173
  hint_used: questionState.attempt > 1,
174
- expected_keywords: significantAnswerTokens(question.answer).slice(0, 6),
175
  subject_id: context.subjectId,
176
  chapter_id: context.chapterId,
177
  daily_task_id: dailyTaskId,
@@ -214,7 +206,6 @@ export function AdaptiveQuizStep({
214
  }
215
  setSubmitting(true);
216
  setSyncError(null);
217
- const clientCorrect = isTransferAnswerCorrect(transfer, transferAnswer);
218
  try {
219
  const context = await resolveContext();
220
  const consequence = await recordLearningCheckpoint({
@@ -226,14 +217,10 @@ export function AdaptiveQuizStep({
226
  kind: "transfer_check",
227
  question_id: transfer.id,
228
  question_type: "short",
229
- prompt: transfer.prompt,
230
  student_answer: transferAnswer,
231
- correct_answer: transfer.answer,
232
- client_correct: clientCorrect,
233
  // This is a different question, not another attempt at the original.
234
  attempt_index: 1,
235
  hint_used: false,
236
- expected_keywords: significantAnswerTokens(transfer.answer).slice(0, 6),
237
  subject_id: context.subjectId,
238
  chapter_id: context.chapterId,
239
  daily_task_id: dailyTaskId,
 
16
  checkpointQuestionType,
17
  firstOpenQuestionIndex,
18
  freshQuestionState,
 
 
19
  minimalHintFor,
 
20
  transferQuestionFor,
21
  type AdaptiveCheckpointState,
22
  } from "./adaptiveCheckpoint";
 
150
  }
151
  setSubmitting(true);
152
  setSyncError(null);
 
153
  try {
154
  const context = await resolveContext();
155
  const consequence = await recordLearningCheckpoint({
 
161
  kind: checkpointKindFor(question),
162
  question_id: question.id,
163
  question_type: checkpointQuestionType(question),
 
164
  student_answer: selected,
 
 
165
  attempt_index: questionState.attempt,
166
  hint_used: questionState.attempt > 1,
 
167
  subject_id: context.subjectId,
168
  chapter_id: context.chapterId,
169
  daily_task_id: dailyTaskId,
 
206
  }
207
  setSubmitting(true);
208
  setSyncError(null);
 
209
  try {
210
  const context = await resolveContext();
211
  const consequence = await recordLearningCheckpoint({
 
217
  kind: "transfer_check",
218
  question_id: transfer.id,
219
  question_type: "short",
 
220
  student_answer: transferAnswer,
 
 
221
  // This is a different question, not another attempt at the original.
222
  attempt_index: 1,
223
  hint_used: false,
 
224
  subject_id: context.subjectId,
225
  chapter_id: context.chapterId,
226
  daily_task_id: dailyTaskId,
src/components/tuition/class/GuidedClass.tsx CHANGED
@@ -3398,14 +3398,15 @@ export function GuidedClass({
3398
  setPracticeSaving(true);
3399
  try {
3400
  const nextAttempt = writtenAttemptCount + 1;
 
3401
  const result = await submitTuitionWrittenAttempt(tuitionSessionId, {
3402
- client_attempt_id: newCheckpointRunId(),
3403
  student_answer: practiceAnswer,
3404
  attempt_index: nextAttempt,
3405
  hint_used: showHint,
3406
  });
3407
  setPracticeSubmitted(true);
3408
- setWrittenAttemptId(result.checkpoint_id);
3409
  setWrittenAttemptCount(nextAttempt);
3410
  setAuthoritativeCorrection(result.correction);
3411
  setTuitionSessionRevision(result.session_revision);
 
3398
  setPracticeSaving(true);
3399
  try {
3400
  const nextAttempt = writtenAttemptCount + 1;
3401
+ const clientAttemptId = newCheckpointRunId();
3402
  const result = await submitTuitionWrittenAttempt(tuitionSessionId, {
3403
+ client_attempt_id: clientAttemptId,
3404
  student_answer: practiceAnswer,
3405
  attempt_index: nextAttempt,
3406
  hint_used: showHint,
3407
  });
3408
  setPracticeSubmitted(true);
3409
+ setWrittenAttemptId(clientAttemptId);
3410
  setWrittenAttemptCount(nextAttempt);
3411
  setAuthoritativeCorrection(result.correction);
3412
  setTuitionSessionRevision(result.session_revision);
src/components/tuition/class/adaptiveCheckpoint.ts CHANGED
@@ -124,6 +124,7 @@ export type TransferQuestion = {
124
  id: string;
125
  prompt: string;
126
  answer: string;
 
127
  };
128
 
129
  /**
@@ -139,10 +140,17 @@ export function transferQuestionFor(
139
  if (!flashcards.length) return null;
140
  const card = flashcards[questionIndex % flashcards.length];
141
  if (!card?.front || !card.back) return null;
 
 
 
 
 
 
142
  return {
143
- id: `transfer-${questionIndex + 1}`,
144
  prompt: card.front,
145
  answer: card.back,
 
146
  };
147
  }
148
 
 
124
  id: string;
125
  prompt: string;
126
  answer: string;
127
+ requiredKeywords?: string[];
128
  };
129
 
130
  /**
 
140
  if (!flashcards.length) return null;
141
  const card = flashcards[questionIndex % flashcards.length];
142
  if (!card?.front || !card.back) return null;
143
+ // A chapter-test question may assess another mission. This mission's
144
+ // revision cards cannot prove transfer of that other concept.
145
+ const assessedMission = session.quiz.questions[questionIndex]?.conceptMissionId ?? session.missionId;
146
+ if (assessedMission !== session.missionId) return null;
147
+ // Reusing the same card through another quiz index is still the same prompt.
148
+ const cardIndex = flashcards.findIndex((item) => item.front === card.front && item.back === card.back);
149
  return {
150
+ id: `${session.chapterId}:${session.missionId}:flashcard-${cardIndex + 1}`,
151
  prompt: card.front,
152
  answer: card.back,
153
+ ...(card.requiredKeywords?.length ? { requiredKeywords: card.requiredKeywords } : {}),
154
  };
155
  }
156
 
src/lib/api/learning-state.ts CHANGED
@@ -688,10 +688,10 @@ export function recordLearningCheckpoint(payload: {
688
  kind: CheckpointKind;
689
  question_id: string;
690
  question_type: "mcq" | "short" | "numerical" | "diagram" | "board";
691
- prompt: string;
692
  student_answer: string;
693
- correct_answer: string;
694
- client_correct: boolean;
695
  attempt_index?: number;
696
  hint_used?: boolean;
697
  expected_keywords?: string[];
 
688
  kind: CheckpointKind;
689
  question_id: string;
690
  question_type: "mcq" | "short" | "numerical" | "diagram" | "board";
691
+ prompt?: string;
692
  student_answer: string;
693
+ correct_answer?: string;
694
+ client_correct?: boolean;
695
  attempt_index?: number;
696
  hint_used?: boolean;
697
  expected_keywords?: string[];
src/lib/teaching/physicsLessonSeeds.ts CHANGED
@@ -213,6 +213,7 @@ export type TuitionLessonSeed = {
213
  flashcards: Array<{
214
  front: string;
215
  back: string;
 
216
  }>;
217
  revisionNotes: string[];
218
  weakAreaTags: string[];
@@ -374,7 +375,7 @@ const M1: TuitionLessonSeed = physicsSeed({
374
  },
375
  revisionSave: {
376
  flashcards: [
377
- { front: "What is frequency?", back: "Number of oscillations per second (Hz)." },
378
  { front: "What is amplitude?", back: "Maximum displacement from equilibrium position." },
379
  ],
380
  revisionNotes: ["f = 1/T", "Amplitude determines how far it swings"],
 
213
  flashcards: Array<{
214
  front: string;
215
  back: string;
216
+ requiredKeywords?: string[];
217
  }>;
218
  revisionNotes: string[];
219
  weakAreaTags: string[];
 
375
  },
376
  revisionSave: {
377
  flashcards: [
378
+ { front: "What is frequency?", back: "Number of oscillations per second (Hz).", requiredKeywords: ["number", "oscillations", "second"] },
379
  { front: "What is amplitude?", back: "Maximum displacement from equilibrium position." },
380
  ],
381
  revisionNotes: ["f = 1/T", "Amplitude determines how far it swings"],
src/lib/tuition/longFormClassRuntime.ts CHANGED
@@ -85,7 +85,7 @@ export type LongFormClassRuntime = {
85
  examPractice: LongFormExamPractice[];
86
  practiceSet: LongFormPracticeItem[];
87
  revisionPack: {
88
- flashcards: Array<{ front: string; back: string }>;
89
  onePageRevision: string[];
90
  lastMinuteMistakes: string[];
91
  };
 
85
  examPractice: LongFormExamPractice[];
86
  practiceSet: LongFormPracticeItem[];
87
  revisionPack: {
88
+ flashcards: Array<{ front: string; back: string; requiredKeywords?: string[] }>;
89
  onePageRevision: string[];
90
  lastMinuteMistakes: string[];
91
  };
tests/checkpoint_helper.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test requests for the published, server-owned Tuition checkpoints.
2
+
3
+ The checkpoint endpoint deliberately does not trust prompt/answer fields sent by
4
+ the browser. Keeping request construction here makes API tests use the same
5
+ authored lesson contract as the application while retaining the old test
6
+ call-site shape (``correct`` and an alias question id).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from functools import lru_cache
12
+ from typing import Any
13
+
14
+ from app.services.tuition_content_contract import load_tuition_content_contract
15
+
16
+
17
+ CHAPTER_ID = "phy-p1-c1"
18
+ MISSION_ID = "M1"
19
+
20
+
21
+ @lru_cache(maxsize=1)
22
+ def _published_questions() -> tuple[dict[str, Any], ...]:
23
+ lesson = load_tuition_content_contract().lesson(CHAPTER_ID, MISSION_ID)
24
+ if lesson is None:
25
+ raise AssertionError(f"published test lesson missing: {CHAPTER_ID}:{MISSION_ID}")
26
+
27
+ # Checkpoint metadata is part of the published contract. Tests must never
28
+ # fabricate an answer or silently fall back to a pre-contract fixture.
29
+ questions = list(lesson.checkpoints)
30
+ if not questions:
31
+ raise AssertionError("published M1 checkpoint metadata is missing")
32
+ return tuple(questions)
33
+
34
+
35
+ def _question(alias: str) -> dict[str, Any]:
36
+ questions = _published_questions()
37
+ raw = alias.rsplit(":", 1)[-1]
38
+ for item in questions:
39
+ authored_id = str(item.get("id") or "")
40
+ source_id = str(item.get("sourceQuestionId") or "")
41
+ if (
42
+ authored_id == alias
43
+ or authored_id == raw
44
+ or authored_id.rsplit(":", 1)[-1] == raw
45
+ or source_id == alias
46
+ or source_id == raw
47
+ or source_id.rsplit(":", 1)[-1] == raw
48
+ ):
49
+ return item
50
+ raise AssertionError(f"unknown authored checkpoint id: {alias!r}")
51
+
52
+
53
+ def checkpoint_payload(
54
+ *,
55
+ event_id: str,
56
+ correct: bool,
57
+ question_id: str = "m1-q1",
58
+ attempt_index: int = 1,
59
+ kind: str | None = None,
60
+ student_answer: str | None = None,
61
+ ) -> dict[str, object]:
62
+ """Build a browser-shaped request backed by an authored question."""
63
+ question = _question(question_id)
64
+ answer = str(question.get("answer") or "")
65
+ submitted = student_answer if student_answer is not None else (answer if correct else "not the authored answer")
66
+ question_kind = str(question.get("kind") or kind or "checkpoint_mcq")
67
+ question_type = str(question.get("type") or "mcq")
68
+ concept_mission = str(question.get("conceptMissionId") or MISSION_ID)
69
+ authored_id = str(question.get("id") or "")
70
+ canonical_id = authored_id if ":" in authored_id else f"{CHAPTER_ID}:{concept_mission}:{authored_id}"
71
+ return {
72
+ "client_event_id": event_id,
73
+ "concept_key": f"{CHAPTER_ID}:{concept_mission}",
74
+ "concept_label": str(question.get("conceptLabel") or "Oscillation, Amplitude, Period and Frequency"),
75
+ "chapter_catalog_id": CHAPTER_ID,
76
+ "mission_id": concept_mission,
77
+ "kind": question_kind,
78
+ "question_id": canonical_id,
79
+ "question_type": question_type,
80
+ "prompt": str(question.get("prompt") or ""),
81
+ "student_answer": submitted,
82
+ # These are retained as browser compatibility fields. The endpoint
83
+ # must ignore them and grade against the authored answer above.
84
+ "correct_answer": answer,
85
+ "client_correct": correct,
86
+ "attempt_index": attempt_index,
87
+ "hint_used": False,
88
+ "expected_keywords": [answer] if answer else [],
89
+ }
tests/test_academic_next_action.py CHANGED
@@ -13,6 +13,7 @@ from app.models.learning_state import RevisionItem, StudentProfileState, TopicMa
13
  from app.services.learning_state_service import read_learning_state
14
  from app.services.today_plan_service import ensure_today_plan
15
  from tests.phase5_tuition_helper import complete_tuition_class
 
16
 
17
 
18
  def _onboarding(*, exam_in_days: int = 60) -> dict[str, object]:
@@ -75,23 +76,8 @@ def _checkpoint(
75
  question_id: str,
76
  attempt_index: int,
77
  ) -> dict[str, object]:
78
- return {
79
- "client_event_id": event_id,
80
- "concept_key": "phy-p1-c1:M1",
81
- "concept_label": "Oscillation, Amplitude, Period and Frequency",
82
- "chapter_catalog_id": "phy-p1-c1",
83
- "mission_id": "M1",
84
- "kind": "checkpoint_mcq",
85
- "question_id": question_id,
86
- "question_type": "mcq",
87
- "prompt": "The SI unit of frequency is:",
88
- "student_answer": "hertz" if correct else "metre",
89
- "correct_answer": "hertz",
90
- "client_correct": correct,
91
- "attempt_index": attempt_index,
92
- "hint_used": False,
93
- "expected_keywords": ["hertz"],
94
- }
95
 
96
 
97
  def test_story_a_correction_and_checkpoint_choose_the_next_exact_lesson(client) -> None:
@@ -123,7 +109,7 @@ def test_story_a_correction_and_checkpoint_choose_the_next_exact_lesson(client)
123
  json=_checkpoint(
124
  event_id="story-a-fixed-1",
125
  correct=True,
126
- question_id="m1-q2",
127
  attempt_index=1,
128
  ),
129
  )
@@ -305,7 +291,7 @@ def test_story_d_wrong_answers_drive_practice_then_correction_updates_mastery(
305
  json=_checkpoint(
306
  event_id=f"story-d-wrong-{attempt}",
307
  correct=False,
308
- question_id=f"m1-wrong-{attempt}",
309
  attempt_index=attempt,
310
  ),
311
  )
@@ -332,7 +318,7 @@ def test_story_d_wrong_answers_drive_practice_then_correction_updates_mastery(
332
  json=_checkpoint(
333
  event_id="story-d-correct-4",
334
  correct=True,
335
- question_id="m1-correct-4",
336
  attempt_index=1,
337
  ),
338
  )
@@ -355,7 +341,7 @@ def test_story_e_exam_near_revision_is_urgent_and_notification_is_stable(
355
  json=_checkpoint(
356
  event_id="story-e-revision-1",
357
  correct=True,
358
- question_id="m1-revision-1",
359
  attempt_index=1,
360
  ),
361
  )
 
13
  from app.services.learning_state_service import read_learning_state
14
  from app.services.today_plan_service import ensure_today_plan
15
  from tests.phase5_tuition_helper import complete_tuition_class
16
+ from tests.checkpoint_helper import checkpoint_payload
17
 
18
 
19
  def _onboarding(*, exam_in_days: int = 60) -> dict[str, object]:
 
76
  question_id: str,
77
  attempt_index: int,
78
  ) -> dict[str, object]:
79
+ return checkpoint_payload(event_id=event_id, correct=correct, question_id=question_id,
80
+ attempt_index=attempt_index)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
 
83
  def test_story_a_correction_and_checkpoint_choose_the_next_exact_lesson(client) -> None:
 
109
  json=_checkpoint(
110
  event_id="story-a-fixed-1",
111
  correct=True,
112
+ question_id="flashcard-1",
113
  attempt_index=1,
114
  ),
115
  )
 
291
  json=_checkpoint(
292
  event_id=f"story-d-wrong-{attempt}",
293
  correct=False,
294
+ question_id="m1-q1",
295
  attempt_index=attempt,
296
  ),
297
  )
 
318
  json=_checkpoint(
319
  event_id="story-d-correct-4",
320
  correct=True,
321
+ question_id="flashcard-1",
322
  attempt_index=1,
323
  ),
324
  )
 
341
  json=_checkpoint(
342
  event_id="story-e-revision-1",
343
  correct=True,
344
+ question_id="m1-q1",
345
  attempt_index=1,
346
  ),
347
  )
tests/test_adaptive_engine.py CHANGED
@@ -9,6 +9,7 @@ from sqlalchemy import select
9
  from app.core.database import SessionLocal
10
  from app.models.learning_state import DailyTask, RepairItem, RevisionItem, TopicMastery
11
  from tests.phase5_tuition_helper import complete_tuition_class
 
12
 
13
 
14
  def _payload(*, subjects: list[str] | None = None, daily_minutes: int = 60) -> dict[str, object]:
@@ -33,23 +34,8 @@ def _checkpoint(
33
  question_id: str = "m1-q1",
34
  student_answer: str | None = None,
35
  ) -> dict[str, object]:
36
- return {
37
- "client_event_id": event_id,
38
- "concept_key": "phy-p1-c1:M1",
39
- "concept_label": "Oscillation, Amplitude, Period and Frequency",
40
- "chapter_catalog_id": "phy-p1-c1",
41
- "mission_id": "M1",
42
- "kind": kind,
43
- "question_id": question_id,
44
- "question_type": "mcq",
45
- "prompt": "The SI unit of frequency is:",
46
- "student_answer": student_answer if student_answer is not None else ("hertz" if correct else "metre"),
47
- "correct_answer": "hertz",
48
- "client_correct": correct,
49
- "attempt_index": attempt_index,
50
- "hint_used": False,
51
- "expected_keywords": ["hertz"],
52
- }
53
 
54
 
55
  def test_wrong_checkpoint_creates_repair_and_mastery_consequence(client) -> None:
@@ -96,7 +82,7 @@ def test_hints_and_retry_context_do_not_credit_independent_mastery(client) -> No
96
  client.post("/learning-state/onboarding", json=_payload())
97
  for index, assistance in enumerate(({"hint_used": True}, {"attempt_index": 2})):
98
  payload = {**_checkpoint(event_id=f"evt-supported-{index}", correct=True,
99
- question_id=f"supported-{index}"), **assistance}
100
  response = client.post("/learning-state/checkpoints", json=payload)
101
  assert response.status_code == 200, response.text
102
  body = response.json()
@@ -135,7 +121,7 @@ def test_repair_remains_in_plan_until_a_fresh_independent_check(client, assistan
135
  task = next(task for task in before["today_plan"]["tasks"] if task["task_type"] == "mistake_repair")
136
  response = client.post("/learning-state/checkpoints", json={
137
  **_checkpoint(event_id="repair-independent-supported", correct=True,
138
- question_id="fresh-transfer", kind="transfer_check"),
139
  "daily_task_id": task["id"],
140
  **assistance,
141
  })
@@ -154,11 +140,11 @@ def test_repair_remains_in_plan_until_a_fresh_independent_check(client, assistan
154
  def test_previously_correct_question_cannot_clear_a_new_repair(client) -> None:
155
  client.post("/learning-state/onboarding", json=_payload())
156
  client.post("/learning-state/checkpoints", json=_checkpoint(
157
- event_id="repair-familiar-correct", correct=True, question_id="known-question"))
158
  client.post("/learning-state/checkpoints", json=_checkpoint(
159
- event_id="repair-familiar-wrong", correct=False, question_id="failed-question"))
160
  response = client.post("/learning-state/checkpoints", json=_checkpoint(
161
- event_id="repair-familiar-repeat", correct=True, question_id="known-question", kind="transfer_check"))
162
  assert response.status_code == 200, response.text
163
  assert response.json()["repair_status"] != "resolved"
164
  assert response.json()["mastery"]["after_state"] == "needs_repair"
@@ -205,7 +191,7 @@ def test_fresh_independent_check_resolves_repair_idempotently(client) -> None:
205
  client.post("/learning-state/checkpoints", json=_checkpoint(event_id="evt-fix-1", correct=False))
206
  fixed = client.post(
207
  "/learning-state/checkpoints",
208
- json=_checkpoint(event_id="evt-fix-2", correct=True, question_id="m1-q2"),
209
  ).json()
210
  assert fixed["repair_status"] == "resolved"
211
  assert fixed["repair_item"]["retry_result"] == "recovered"
@@ -215,7 +201,7 @@ def test_fresh_independent_check_resolves_repair_idempotently(client) -> None:
215
  # Re-sending the independent check does not resurrect or duplicate anything.
216
  replay = client.post(
217
  "/learning-state/checkpoints",
218
- json=_checkpoint(event_id="evt-fix-2", correct=True, question_id="m1-q2"),
219
  ).json()
220
  assert replay["replayed"] is True
221
 
@@ -355,7 +341,7 @@ def test_kerala_student_profile_drives_repair_revision_and_tomorrow_plan(
355
  event_id="kerala-loop-retry-2",
356
  correct=True,
357
  attempt_index=1,
358
- question_id="m1-transfer-2",
359
  ),
360
  )
361
  assert recovered.status_code == 200, recovered.text
@@ -379,7 +365,7 @@ def test_plan_today_schedules_due_revision_and_cancels_stale_ones(client) -> Non
379
  client.post("/learning-state/onboarding", json=_payload())
380
  client.post(
381
  "/learning-state/checkpoints",
382
- json=_checkpoint(event_id="evt-rev-1", correct=True, question_id="m1-q9"),
383
  )
384
  due_at = datetime.now(timezone.utc) - timedelta(hours=2)
385
  with SessionLocal() as db:
@@ -408,7 +394,7 @@ def test_plan_today_schedules_due_revision_and_cancels_stale_ones(client) -> Non
408
  # The student revises (mastery engine pushes next_review_at forward).
409
  client.post(
410
  "/learning-state/checkpoints",
411
- json=_checkpoint(event_id="evt-rev-2", correct=True, kind="revision_recall", question_id="m1-q10"),
412
  )
413
  cleaned = client.get("/learning-state/today-plan").json()
414
  assert all(
 
9
  from app.core.database import SessionLocal
10
  from app.models.learning_state import DailyTask, RepairItem, RevisionItem, TopicMastery
11
  from tests.phase5_tuition_helper import complete_tuition_class
12
+ from tests.checkpoint_helper import checkpoint_payload
13
 
14
 
15
  def _payload(*, subjects: list[str] | None = None, daily_minutes: int = 60) -> dict[str, object]:
 
34
  question_id: str = "m1-q1",
35
  student_answer: str | None = None,
36
  ) -> dict[str, object]:
37
+ return checkpoint_payload(event_id=event_id, correct=correct, attempt_index=attempt_index,
38
+ kind=kind, question_id=question_id, student_answer=student_answer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
 
41
  def test_wrong_checkpoint_creates_repair_and_mastery_consequence(client) -> None:
 
82
  client.post("/learning-state/onboarding", json=_payload())
83
  for index, assistance in enumerate(({"hint_used": True}, {"attempt_index": 2})):
84
  payload = {**_checkpoint(event_id=f"evt-supported-{index}", correct=True,
85
+ question_id="m1-q1"), **assistance}
86
  response = client.post("/learning-state/checkpoints", json=payload)
87
  assert response.status_code == 200, response.text
88
  body = response.json()
 
121
  task = next(task for task in before["today_plan"]["tasks"] if task["task_type"] == "mistake_repair")
122
  response = client.post("/learning-state/checkpoints", json={
123
  **_checkpoint(event_id="repair-independent-supported", correct=True,
124
+ question_id="flashcard-1", kind="transfer_check"),
125
  "daily_task_id": task["id"],
126
  **assistance,
127
  })
 
140
  def test_previously_correct_question_cannot_clear_a_new_repair(client) -> None:
141
  client.post("/learning-state/onboarding", json=_payload())
142
  client.post("/learning-state/checkpoints", json=_checkpoint(
143
+ event_id="repair-familiar-correct", correct=True, question_id="m1-q1"))
144
  client.post("/learning-state/checkpoints", json=_checkpoint(
145
+ event_id="repair-familiar-wrong", correct=False, question_id="flashcard-1"))
146
  response = client.post("/learning-state/checkpoints", json=_checkpoint(
147
+ event_id="repair-familiar-repeat", correct=True, question_id="m1-q1", kind="transfer_check"))
148
  assert response.status_code == 200, response.text
149
  assert response.json()["repair_status"] != "resolved"
150
  assert response.json()["mastery"]["after_state"] == "needs_repair"
 
191
  client.post("/learning-state/checkpoints", json=_checkpoint(event_id="evt-fix-1", correct=False))
192
  fixed = client.post(
193
  "/learning-state/checkpoints",
194
+ json=_checkpoint(event_id="evt-fix-2", correct=True, question_id="flashcard-1"),
195
  ).json()
196
  assert fixed["repair_status"] == "resolved"
197
  assert fixed["repair_item"]["retry_result"] == "recovered"
 
201
  # Re-sending the independent check does not resurrect or duplicate anything.
202
  replay = client.post(
203
  "/learning-state/checkpoints",
204
+ json=_checkpoint(event_id="evt-fix-2", correct=True, question_id="flashcard-1"),
205
  ).json()
206
  assert replay["replayed"] is True
207
 
 
341
  event_id="kerala-loop-retry-2",
342
  correct=True,
343
  attempt_index=1,
344
+ question_id="flashcard-1",
345
  ),
346
  )
347
  assert recovered.status_code == 200, recovered.text
 
365
  client.post("/learning-state/onboarding", json=_payload())
366
  client.post(
367
  "/learning-state/checkpoints",
368
+ json=_checkpoint(event_id="evt-rev-1", correct=True, question_id="m1-q1"),
369
  )
370
  due_at = datetime.now(timezone.utc) - timedelta(hours=2)
371
  with SessionLocal() as db:
 
394
  # The student revises (mastery engine pushes next_review_at forward).
395
  client.post(
396
  "/learning-state/checkpoints",
397
+ json=_checkpoint(event_id="evt-rev-2", correct=True, kind="revision_recall", question_id="flashcard-1"),
398
  )
399
  cleaned = client.get("/learning-state/today-plan").json()
400
  assert all(
tests/test_checkpoint_authority.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Published question content, not browser claims, controls mastery."""
2
+ from __future__ import annotations
3
+
4
+ import pytest
5
+ from sqlalchemy import select
6
+
7
+ from app.core.database import SessionLocal
8
+ from app.models.learning_state import CheckpointEvent, LearningEvent, RepairItem, RevisionItem, TopicMastery
9
+ from app.services.checkpoint_evaluation import _grade
10
+ from app.services.tuition_content_contract import load_tuition_content_contract
11
+
12
+
13
+ def payload(**changes):
14
+ return {"client_event_id": "authority-attempt-001", "concept_key": "phy-p1-c1:M1",
15
+ "concept_label": "Forged label", "chapter_catalog_id": "phy-p1-c1", "mission_id": "M1",
16
+ "kind": "checkpoint_mcq", "question_id": "m1-q1", "question_type": "mcq",
17
+ "student_answer": "hertz", **changes}
18
+
19
+
20
+ @pytest.mark.parametrize("answer,client_key,client_flag,expected", [
21
+ ("metre", "metre", True, False), ("hertz", "metre", False, True),
22
+ ("HERTZ", "bogus", False, True), ("", "", True, False),
23
+ ])
24
+ def test_mcq_grades_server_answer_even_when_browser_lies(client, answer, client_key, client_flag, expected):
25
+ response = client.post("/learning-state/checkpoints", json=payload(
26
+ student_answer=answer, correct_answer=client_key, client_correct=client_flag,
27
+ prompt="Browser replaced this question", expected_keywords=["metre"]))
28
+ assert response.status_code == 200, response.text
29
+ assert response.json()["correct"] is expected
30
+ with SessionLocal() as db:
31
+ event = db.scalar(select(CheckpointEvent))
32
+ assert event.question_id == "phy-p1-c1:M1:m1-q1"
33
+ assert event.payload["correct_answer"] == "hertz"
34
+ assert event.payload["prompt"] != "Browser replaced this question"
35
+ assert event.payload["evaluation_version"] == "authored-checkpoint-v1"
36
+
37
+
38
+ @pytest.mark.parametrize("changes", [
39
+ {"question_id": "made-up"}, {"question_id": "transfer-1"},
40
+ {"mission_id": "M2"}, {"concept_key": "phy-p1-c1:M2"},
41
+ {"chapter_catalog_id": "unpublished-chapter"},
42
+ {"question_id": "phy-p1-c1:M1:your-turn"},
43
+ {"chapter_id": "other-students-chapter"}, {"subject_id": "other-students-subject"},
44
+ {"trusted_correct": True},
45
+ ])
46
+ def test_unregistered_or_cross_context_evidence_cannot_mutate_student_state(client, changes):
47
+ response = client.post("/learning-state/checkpoints", json=payload(**changes))
48
+ assert response.status_code in {404, 422}, response.text
49
+ with SessionLocal() as db:
50
+ for model in (CheckpointEvent, TopicMastery, RepairItem, RevisionItem, LearningEvent):
51
+ assert db.scalar(select(model)) is None
52
+
53
+
54
+ def test_browser_cannot_promote_mcq_to_board_or_numerical_mastery(client):
55
+ response = client.post("/learning-state/checkpoints", json=payload(
56
+ kind="board_answer", question_type="numerical", difficulty="hard"))
57
+ assert response.status_code == 200, response.text
58
+ with SessionLocal() as db:
59
+ event = db.scalar(select(CheckpointEvent))
60
+ assert event.kind == "checkpoint_mcq"
61
+ assert event.payload["question_type"] == "mcq"
62
+
63
+
64
+ def test_transfer_uses_authored_card_and_dampens_repeats(client):
65
+ lesson = load_tuition_content_contract().lesson("phy-p1-c1", "M1")
66
+ card = next(q for q in lesson.checkpoints if q["kind"] == "transfer_check")
67
+ body = payload(question_id=card["id"], student_answer=card["answer"],
68
+ correct_answer="invented answer", client_correct=False)
69
+ first = client.post("/learning-state/checkpoints", json=body)
70
+ assert first.status_code == 200, first.text
71
+ assert first.json()["correct"] is True
72
+ second = client.post("/learning-state/checkpoints", json={**body, "client_event_id": "authority-repeat-002"})
73
+ assert second.status_code == 200, second.text
74
+ with SessionLocal() as db:
75
+ mastery = db.scalar(select(TopicMastery))
76
+ assert mastery.evidence["log"][-1]["strength"] == pytest.approx(0.55 * 0.25)
77
+ assert mastery.evidence["consecutive_success"] == 1
78
+
79
+
80
+ @pytest.mark.parametrize("answer,expected", [
81
+ ("Frequency is the number of oscillations per second.", True),
82
+ ("The number of oscillations per second (Hz).", True),
83
+ ("oscillations", False),
84
+ ("Frequency is not the number of oscillations per second.", False),
85
+ ("Frequency is the number of oscillations per minute.", False),
86
+ ])
87
+ def test_definition_uses_authored_scoring_points_not_optional_unit_annotation(client, answer, expected):
88
+ response = client.post("/learning-state/checkpoints", json=payload(
89
+ question_id="phy-p1-c1:M1:flashcard-1", student_answer=answer,
90
+ expected_keywords=["oscillations"], client_correct=not expected))
91
+ assert response.status_code == 200, response.text
92
+ assert response.json()["correct"] is expected
93
+
94
+
95
+ def test_same_intent_cannot_replay_against_another_answer(client):
96
+ first = client.post("/learning-state/checkpoints", json=payload())
97
+ assert first.status_code == 200, first.text
98
+ replay = client.post("/learning-state/checkpoints", json=payload())
99
+ assert replay.status_code == 200 and replay.json()["replayed"]
100
+ changed = client.post("/learning-state/checkpoints", json=payload(student_answer="metre"))
101
+ assert changed.status_code == 409
102
+ with SessionLocal() as db:
103
+ assert len(list(db.scalars(select(CheckpointEvent)))) == 1
104
+ assert db.scalar(select(TopicMastery)).attempts_count == 1
105
+
106
+
107
+ def test_old_raw_prompt_identity_does_not_become_fresh_after_canonicalization(client):
108
+ first = client.post("/learning-state/checkpoints", json=payload())
109
+ assert first.status_code == 200
110
+ with SessionLocal() as db:
111
+ event = db.scalar(select(CheckpointEvent))
112
+ event.question_id = "m1-q1"
113
+ mastery = db.scalar(select(TopicMastery))
114
+ mastery.evidence = {**mastery.evidence, "seen_question_correct": ["m1-q1"]}
115
+ db.commit()
116
+ second = client.post("/learning-state/checkpoints", json=payload(client_event_id="canonical-upgrade-repeat"))
117
+ assert second.status_code == 200, second.text
118
+ with SessionLocal() as db:
119
+ mastery = db.scalar(select(TopicMastery))
120
+ assert mastery.evidence["log"][-1]["strength"] == pytest.approx(0.45 * 0.25)
121
+ assert mastery.evidence["log"][-1]["streak_credited"] is False
122
+
123
+
124
+ def test_chapter_test_prompt_maps_only_to_its_authored_concept(client):
125
+ lesson = load_tuition_content_contract().lesson("phy-p1-c1", "M9")
126
+ question = lesson.checkpoints[0]
127
+ response = client.post("/learning-state/checkpoints", json=payload(
128
+ question_id=question["sourceQuestionId"], student_answer=question["answer"]))
129
+ assert response.status_code == 200 and response.json()["correct"], response.text
130
+ wrong_concept = client.post("/learning-state/checkpoints", json=payload(
131
+ client_event_id="chapter-test-wrong-concept", mission_id="M2", concept_key="phy-p1-c1:M2",
132
+ question_id=question["sourceQuestionId"], student_answer=question["answer"]))
133
+ assert wrong_concept.status_code == 422
134
+
135
+
136
+ @pytest.mark.parametrize("answer,expected", [
137
+ ("10 Hz", True), ("10 hertz", True), ("f = 20 / 2 = 10 Hz", True),
138
+ ("20 Hz", False), ("10", False), ("10 m", False), ("10 Hz then 20 Hz", False),
139
+ ])
140
+ def test_numerical_grades_final_value_and_unit(client, answer, expected):
141
+ response = client.post("/learning-state/checkpoints", json=payload(
142
+ client_event_id="numeric-authority-001", mission_id="M5", concept_key="phy-p1-c1:M5",
143
+ question_id="m5-q1", student_answer=answer, client_correct=not expected))
144
+ assert response.status_code == 200, response.text
145
+ assert response.json()["correct"] is expected
146
+
147
+
148
+ def test_short_recall_does_not_pass_from_one_keyword_or_negation():
149
+ expected = "Number of oscillations per second"
150
+ assert _grade(answer="oscillations", expected=expected, question_type="short") is False
151
+ assert _grade(answer="It is not the number of oscillations per second", expected=expected, question_type="short") is False
152
+ assert _grade(answer="The number of oscillations per second", expected=expected, question_type="short") is True
153
+
154
+
155
+ def test_every_published_checkpoint_has_a_bounded_identity_and_accepts_its_authored_answer():
156
+ for lesson in load_tuition_content_contract().lessons:
157
+ assert lesson.checkpoints
158
+ for question in lesson.checkpoints:
159
+ assert len(question["id"]) <= 120
160
+ assert _grade(answer=question["answer"], expected=question["answer"], question_type=question["type"]), question
161
+
162
+
163
+ @pytest.mark.parametrize("expected,answer", [
164
+ ("1/v = 1/20 + 1/(−30) = 1/60 → v = 60 cm (real).", "0.6 m"),
165
+ ("f = 1/P = 1/4 = 0.25 m = 25 cm (convex).", "0.25 m"),
166
+ ("f = 1/P = 1/(-4) = -0.25 m = -25 cm; concave lens", "-25 cm"),
167
+ ])
168
+ def test_numerical_recognizes_reviewed_unit_equivalents(expected, answer):
169
+ assert _grade(answer=answer, expected=expected, question_type="numerical")
170
+
171
+
172
+ def test_additive_checkpoint_export_does_not_invalidate_saved_written_sessions():
173
+ lesson = load_tuition_content_contract().lesson("phy-p1-c1", "M1")
174
+ # Golden pre-checkpoint fingerprint. This remains hermetic in a shallow
175
+ # CI checkout; release verification separately compared all 119 lessons.
176
+ assert lesson.content_fingerprint == "a3321d684cac4e6506d99cd4b5ea46a31e48a68ff56e3bb81aae53ec3da17fd0"
177
+ assert lesson.checkpoints
tests/test_learning_state.py CHANGED
@@ -13,6 +13,7 @@ from app.models.learning_state import (
13
  StudySession,
14
  )
15
  from tests.phase5_tuition_helper import complete_tuition_class
 
16
 
17
 
18
  def _payload(*, subjects: list[str] | None = None) -> dict[str, object]:
@@ -858,20 +859,8 @@ def test_successful_repair_removes_the_pending_repair_from_the_current_plan(clie
858
  for chapter in state["chapters"]
859
  if chapter["catalog_id"] == task["target"]["chapter_catalog_id"]
860
  )
861
- base = {
862
- "concept_key": "sound-frequency",
863
- "concept_label": "Frequency and period",
864
- "chapter_catalog_id": task["target"]["chapter_catalog_id"],
865
- "mission_id": task["mission_id"],
866
- "question_id": "frequency-check",
867
- "question_type": "short",
868
- "prompt": "What is frequency?",
869
- "correct_answer": "Number of oscillations per second",
870
- "expected_keywords": ["oscillations", "second"],
871
- "subject_id": subject_id,
872
- "chapter_id": chapter_id,
873
- "daily_task_id": task["id"],
874
- }
875
  wrong = client.post(
876
  "/learning-state/checkpoints",
877
  json={
@@ -891,9 +880,9 @@ def test_successful_repair_removes_the_pending_repair_from_the_current_plan(clie
891
  json={
892
  **base,
893
  "client_event_id": "repair-recover-checkpoint-002",
894
- "question_id": "repair-fresh-transfer-question",
895
  "kind": "transfer_check",
896
- "student_answer": "Number of oscillations per second",
897
  "client_correct": True,
898
  "attempt_index": 1,
899
  },
 
13
  StudySession,
14
  )
15
  from tests.phase5_tuition_helper import complete_tuition_class
16
+ from tests.checkpoint_helper import checkpoint_payload
17
 
18
 
19
  def _payload(*, subjects: list[str] | None = None) -> dict[str, object]:
 
859
  for chapter in state["chapters"]
860
  if chapter["catalog_id"] == task["target"]["chapter_catalog_id"]
861
  )
862
+ base = {**checkpoint_payload(event_id="unused", correct=False),
863
+ "subject_id": subject_id, "chapter_id": chapter_id, "daily_task_id": task["id"]}
 
 
 
 
 
 
 
 
 
 
 
 
864
  wrong = client.post(
865
  "/learning-state/checkpoints",
866
  json={
 
880
  json={
881
  **base,
882
  "client_event_id": "repair-recover-checkpoint-002",
883
+ "question_id": checkpoint_payload(event_id="unused", correct=True, question_id="flashcard-1")["question_id"],
884
  "kind": "transfer_check",
885
+ "student_answer": "Number of oscillations per second (Hz).",
886
  "client_correct": True,
887
  "attempt_index": 1,
888
  },
tests/test_phase4_release_gate.py CHANGED
@@ -42,6 +42,7 @@ from app.services.planning_context import (
42
  from app.services.planning_policy import build_candidates, select_today_tasks
43
  from app.services.today_plan_service import ensure_today_plan, replan_today
44
  from tests.phase5_tuition_helper import complete_tuition_class
 
45
 
46
 
47
  CLOCK = datetime(2026, 8, 16, 10, 0, tzinfo=timezone.utc)
@@ -121,21 +122,7 @@ def _payload(*, daily_minutes: int = 60, exam_in_days: int | None = 60) -> dict[
121
 
122
 
123
  def _checkpoint(*, event_id: str, correct: bool, attempt_index: int = 1) -> dict[str, object]:
124
- return {
125
- "client_event_id": event_id,
126
- "concept_key": "phy-p1-c1:M1",
127
- "concept_label": "Oscillation, Amplitude, Period and Frequency",
128
- "chapter_catalog_id": "phy-p1-c1",
129
- "mission_id": "M1",
130
- "kind": "checkpoint_mcq",
131
- "question_id": f"q-{event_id}",
132
- "question_type": "mcq",
133
- "prompt": "The SI unit of frequency is:",
134
- "student_answer": "hertz" if correct else "metre",
135
- "correct_answer": "hertz",
136
- "client_correct": correct,
137
- "attempt_index": attempt_index,
138
- }
139
 
140
 
141
  def _dump_tasks(label: str, tasks: list[dict]) -> None:
@@ -1072,8 +1059,7 @@ def test_day1_day2_day3_acceptance_and_reconciliation(client) -> None:
1072
 
1073
  repaired = client.post(
1074
  "/learning-state/checkpoints",
1075
- json={**_checkpoint(event_id="day2-repair-success", correct=True),
1076
- "question_id": "day2-fresh-repair-check"},
1077
  )
1078
  assert repaired.status_code == 200, repaired.text
1079
  assert repaired.json()["repair_status"] == "resolved"
 
42
  from app.services.planning_policy import build_candidates, select_today_tasks
43
  from app.services.today_plan_service import ensure_today_plan, replan_today
44
  from tests.phase5_tuition_helper import complete_tuition_class
45
+ from tests.checkpoint_helper import checkpoint_payload
46
 
47
 
48
  CLOCK = datetime(2026, 8, 16, 10, 0, tzinfo=timezone.utc)
 
122
 
123
 
124
  def _checkpoint(*, event_id: str, correct: bool, attempt_index: int = 1) -> dict[str, object]:
125
+ return checkpoint_payload(event_id=event_id, correct=correct, attempt_index=attempt_index)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
 
128
  def _dump_tasks(label: str, tasks: list[dict]) -> None:
 
1059
 
1060
  repaired = client.post(
1061
  "/learning-state/checkpoints",
1062
+ json=checkpoint_payload(event_id="day2-repair-success", correct=True, question_id="flashcard-1"),
 
1063
  )
1064
  assert repaired.status_code == 200, repaired.text
1065
  assert repaired.json()["repair_status"] == "resolved"
tests/test_phase4_today_plan.py CHANGED
@@ -22,6 +22,7 @@ from app.services.planning_context import (
22
  )
23
  from app.services.planning_policy import select_today_tasks
24
  from app.services.study_schedule import KERALA_TIMEZONE
 
25
 
26
 
27
  def _payload(*, daily_minutes: int = 60, subjects: list[str] | None = None) -> dict[str, object]:
@@ -236,21 +237,7 @@ def test_day_two_plan_remembers_unfinished_repair(client) -> None:
236
  client.post("/learning-state/onboarding", json=_payload())
237
  wrong = client.post(
238
  "/learning-state/checkpoints",
239
- json={
240
- "client_event_id": "phase4-day1-wrong",
241
- "concept_key": "phy-p1-c1:M1",
242
- "concept_label": "Oscillation, Amplitude, Period and Frequency",
243
- "chapter_catalog_id": "phy-p1-c1",
244
- "mission_id": "M1",
245
- "kind": "checkpoint_mcq",
246
- "question_id": "m1-q1",
247
- "question_type": "mcq",
248
- "prompt": "The SI unit of frequency is:",
249
- "student_answer": "metre",
250
- "correct_answer": "hertz",
251
- "client_correct": False,
252
- "attempt_index": 1,
253
- },
254
  )
255
  assert wrong.status_code == 200, wrong.text
256
  assert wrong.json()["repair_status"] == "created"
@@ -260,21 +247,7 @@ def test_day_two_plan_remembers_unfinished_repair(client) -> None:
260
 
261
  repaired = client.post(
262
  "/learning-state/checkpoints",
263
- json={
264
- "client_event_id": "phase4-day2-fixed",
265
- "concept_key": "phy-p1-c1:M1",
266
- "concept_label": "Oscillation, Amplitude, Period and Frequency",
267
- "chapter_catalog_id": "phy-p1-c1",
268
- "mission_id": "M1",
269
- "kind": "checkpoint_mcq",
270
- "question_id": "m1-q2",
271
- "question_type": "mcq",
272
- "prompt": "The SI unit of frequency is:",
273
- "student_answer": "hertz",
274
- "correct_answer": "hertz",
275
- "client_correct": True,
276
- "attempt_index": 1,
277
- },
278
  )
279
  assert repaired.status_code == 200, repaired.text
280
  assert repaired.json()["repair_status"] == "resolved"
 
22
  )
23
  from app.services.planning_policy import select_today_tasks
24
  from app.services.study_schedule import KERALA_TIMEZONE
25
+ from tests.checkpoint_helper import checkpoint_payload
26
 
27
 
28
  def _payload(*, daily_minutes: int = 60, subjects: list[str] | None = None) -> dict[str, object]:
 
237
  client.post("/learning-state/onboarding", json=_payload())
238
  wrong = client.post(
239
  "/learning-state/checkpoints",
240
+ json=checkpoint_payload(event_id="phase4-day1-wrong", correct=False),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  )
242
  assert wrong.status_code == 200, wrong.text
243
  assert wrong.json()["repair_status"] == "created"
 
247
 
248
  repaired = client.post(
249
  "/learning-state/checkpoints",
250
+ json=checkpoint_payload(event_id="phase4-day2-fixed", correct=True, question_id="flashcard-1"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  )
252
  assert repaired.status_code == 200, repaired.text
253
  assert repaired.json()["repair_status"] == "resolved"
tests/test_phase5_tuition_sessions.py CHANGED
@@ -185,7 +185,10 @@ def test_tuition_contract_is_published_and_source_backed() -> None:
185
  assert contract.lesson("geo-part1-ch01-weather-and-climate", "M1") is not None
186
 
187
 
188
- def test_authoritative_tuition_session_requires_real_evidence_and_is_idempotent(auth_client) -> None:
 
 
 
189
  token = _signup(auth_client, "phase5-tuition-a@example.com")
190
  task = _onboard(auth_client, token)
191
  session = _start(auth_client, token, task)
@@ -257,10 +260,21 @@ def test_authoritative_tuition_session_requires_real_evidence_and_is_idempotent(
257
 
258
  current = auth_client.get(f"/tuition-sessions/{session['id']}", headers=_headers(token))
259
  assert current.status_code == 200, current.text
 
 
 
 
 
 
 
 
 
 
 
260
  saved = auth_client.put(
261
  f"/tuition-sessions/{session['id']}",
262
  headers=_headers(token),
263
- json={"client_revision": current.json()["revision"], "state": _state(current.json())},
264
  )
265
  assert saved.status_code == 200, saved.text
266
  completed = auth_client.post(
 
185
  assert contract.lesson("geo-part1-ch01-weather-and-climate", "M1") is not None
186
 
187
 
188
+ @pytest.mark.parametrize("identity_style", ["client_attempt", "event_row"])
189
+ def test_authoritative_tuition_session_requires_real_evidence_and_is_idempotent(
190
+ auth_client, identity_style: str,
191
+ ) -> None:
192
  token = _signup(auth_client, "phase5-tuition-a@example.com")
193
  task = _onboard(auth_client, token)
194
  session = _start(auth_client, token, task)
 
260
 
261
  current = auth_client.get(f"/tuition-sessions/{session['id']}", headers=_headers(token))
262
  assert current.status_code == 200, current.text
263
+ state = _state(current.json())
264
+ if identity_style == "event_row":
265
+ # A legacy browser draft stored the database checkpoint id instead of
266
+ # the client event id. Completion must still resolve that row through
267
+ # the server-owned evidence contract.
268
+ with SessionLocal() as db:
269
+ written_event = db.scalar(
270
+ select(CheckpointEvent).where(CheckpointEvent.client_event_id == attempt_id)
271
+ )
272
+ assert written_event is not None
273
+ state["written_attempt_id"] = written_event.id
274
  saved = auth_client.put(
275
  f"/tuition-sessions/{session['id']}",
276
  headers=_headers(token),
277
+ json={"client_revision": current.json()["revision"], "state": state},
278
  )
279
  assert saved.status_code == 200, saved.text
280
  completed = auth_client.post(
tests/test_revision_reactivation.py CHANGED
@@ -75,9 +75,16 @@ def test_forgotten_review_reopens_same_item_and_preserves_history(client, clock,
75
 
76
  # A lost-response retry cannot restart the cycle or change the recall date.
77
  clock[0] += timedelta(hours=2)
78
- replay = client.post("/learning-state/checkpoints", json={**payload, "student_answer": "hertz"})
79
  assert replay.status_code == 200, replay.text
80
  assert replay.json()["replayed"] is True
 
 
 
 
 
 
 
81
  with SessionLocal() as db:
82
  item = db.get(RevisionItem, item_id)
83
  assert item.due_at.replace(tzinfo=timezone.utc) == expected_due
 
75
 
76
  # A lost-response retry cannot restart the cycle or change the recall date.
77
  clock[0] += timedelta(hours=2)
78
+ replay = client.post("/learning-state/checkpoints", json=payload)
79
  assert replay.status_code == 200, replay.text
80
  assert replay.json()["replayed"] is True
81
+
82
+ # Reusing an event id with a changed answer is tampering, not a replay.
83
+ tampered = client.post(
84
+ "/learning-state/checkpoints",
85
+ json={**payload, "student_answer": "hertz"},
86
+ )
87
+ assert tampered.status_code == 409, tampered.text
88
  with SessionLocal() as db:
89
  item = db.get(RevisionItem, item_id)
90
  assert item.due_at.replace(tzinfo=timezone.utc) == expected_due
tests/test_student_brain_context.py CHANGED
@@ -14,6 +14,7 @@ from app.schemas.student_brain import StudentBrainContext
14
  from app.schemas.tuition_brain import BrainMission, BrainProfile
15
  from app.services.student_brain_context import render_student_brain_prompt
16
  from app.services.tuition_brain_service import profile_from_student_brain
 
17
 
18
 
19
  def _signup(client, email: str) -> str:
@@ -198,20 +199,10 @@ def test_checkpoint_updates_brain_without_exposing_raw_answer(client) -> None:
198
  response = client.post(
199
  "/learning-state/checkpoints",
200
  json={
 
 
201
  "client_event_id": "brain-checkpoint-wrong-001",
202
- "concept_key": "sound-frequency",
203
- "concept_label": "Frequency and period",
204
- "chapter_catalog_id": chapter["catalog_id"],
205
- "mission_id": task["mission_id"],
206
- "kind": "checkpoint_short",
207
- "question_id": "frequency-brain-check",
208
- "question_type": "short",
209
- "prompt": "What is frequency?",
210
- "student_answer": "RAW_PRIVATE_WRONG_ANSWER",
211
- "correct_answer": "Number of oscillations per second",
212
- "client_correct": False,
213
  "attempt_index": 1,
214
- "expected_keywords": ["oscillations", "second"],
215
  "time_spent_seconds": 75,
216
  "difficulty": "hard",
217
  "skill_tags": ["definition", "recall"],
@@ -235,11 +226,11 @@ def test_checkpoint_updates_brain_without_exposing_raw_answer(client) -> None:
235
  assert mistake.error_type == "time_pressure"
236
  assert mistake.error_type_source == "student_reflection"
237
  assert mistake.internal_error_category == "concept_misunderstanding"
238
- assert mistake.difficulty == "hard"
239
  assert mistake.time_spent_seconds == 75
240
  assert mistake.skill_tags == ["concepts"]
241
  assert brain.recent_question_attempts[0].correct is False
242
- assert brain.recent_question_attempts[0].difficulty == "hard"
243
  assert brain.recent_question_attempts[0].skill_tags == ["concepts"]
244
  readiness = brain.weakest_topics[0].skill_readiness[0]
245
  assert readiness.skill == "concepts"
@@ -264,20 +255,9 @@ def test_skill_readiness_does_not_count_hints_or_retries_as_independent_success(
264
  response = client.post(
265
  "/learning-state/checkpoints",
266
  json={
267
- "client_event_id": f"brain-readiness-{event_id}",
268
- "concept_key": "sound-frequency-readiness",
269
- "concept_label": "Frequency",
270
- "chapter_catalog_id": "phy-p1-c1",
271
- "mission_id": "M1",
272
- "kind": "checkpoint_short",
273
- "question_id": f"frequency-{event_id}",
274
- "question_type": "short",
275
- "prompt": "What is the SI unit of frequency?",
276
- "student_answer": answer,
277
- "correct_answer": "hertz",
278
- "expected_keywords": ["hertz"],
279
- "client_correct": answer == "hertz",
280
- "attempt_index": attempt_index,
281
  "hint_used": hint_used,
282
  "skill_tags": ["formula"],
283
  },
@@ -285,11 +265,11 @@ def test_skill_readiness_does_not_count_hints_or_retries_as_independent_success(
285
  assert response.status_code == 200, response.text
286
 
287
  brain = client.get("/learning-state/brain-context").json()
288
- topic = next(item for item in brain["weakest_topics"] if item["topic_key"] == "sound-frequency-readiness")
289
  assert topic["skill_readiness"] == [
290
  {
291
- "skill": "formulas",
292
- "label": "Formula recall",
293
  "score": 0,
294
  "attempts": 1,
295
  "correct_attempts": 0,
 
14
  from app.schemas.tuition_brain import BrainMission, BrainProfile
15
  from app.services.student_brain_context import render_student_brain_prompt
16
  from app.services.tuition_brain_service import profile_from_student_brain
17
+ from tests.checkpoint_helper import checkpoint_payload
18
 
19
 
20
  def _signup(client, email: str) -> str:
 
199
  response = client.post(
200
  "/learning-state/checkpoints",
201
  json={
202
+ **checkpoint_payload(event_id="brain-checkpoint-wrong-001", correct=False,
203
+ student_answer="RAW_PRIVATE_WRONG_ANSWER"),
204
  "client_event_id": "brain-checkpoint-wrong-001",
 
 
 
 
 
 
 
 
 
 
 
205
  "attempt_index": 1,
 
206
  "time_spent_seconds": 75,
207
  "difficulty": "hard",
208
  "skill_tags": ["definition", "recall"],
 
226
  assert mistake.error_type == "time_pressure"
227
  assert mistake.error_type_source == "student_reflection"
228
  assert mistake.internal_error_category == "concept_misunderstanding"
229
+ assert mistake.difficulty == "easy"
230
  assert mistake.time_spent_seconds == 75
231
  assert mistake.skill_tags == ["concepts"]
232
  assert brain.recent_question_attempts[0].correct is False
233
+ assert brain.recent_question_attempts[0].difficulty == "easy"
234
  assert brain.recent_question_attempts[0].skill_tags == ["concepts"]
235
  readiness = brain.weakest_topics[0].skill_readiness[0]
236
  assert readiness.skill == "concepts"
 
255
  response = client.post(
256
  "/learning-state/checkpoints",
257
  json={
258
+ **checkpoint_payload(event_id=f"brain-readiness-{event_id}",
259
+ correct=answer == "hertz", student_answer=answer,
260
+ attempt_index=attempt_index),
 
 
 
 
 
 
 
 
 
 
 
261
  "hint_used": hint_used,
262
  "skill_tags": ["formula"],
263
  },
 
265
  assert response.status_code == 200, response.text
266
 
267
  brain = client.get("/learning-state/brain-context").json()
268
+ topic = next(item for item in brain["weakest_topics"] if item["topic_key"] == "phy-p1-c1:M1")
269
  assert topic["skill_readiness"] == [
270
  {
271
+ "skill": "concepts",
272
+ "label": "Concept understanding",
273
  "score": 0,
274
  "attempts": 1,
275
  "correct_attempts": 0,