File size: 7,251 Bytes
1289247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""Per-learner state for retrieval practice: what's been covered, and a successive-
relearning schedule per topic. Deterministic, JSON on disk, no LLM in the loop.

Scheduling model (see ARCHITECTURE.md §Learning science):
- Successive relearning (Rawson & Dunlosky 2011, 2018): a topic counts as successfully
  relearned in a quiz session when every item on it is answered correctly (criterion =
  one correct recall per session). Each success moves it one step up an expanding
  interval ladder (1, 3, 7, 21, 60 days); a miss drops it back to a 1-day interval.
- After RELEARNING_SESSIONS_FOR_DURABLE spaced successes the topic is "durable" and is
  only revisited on its long interval (maintenance), mirroring the ~3-session finding.
- Expanding gaps follow Cepeda et al. (2008): the optimal gap grows with the retention
  interval you care about.
"""

from __future__ import annotations

import json
import re
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone

from src.config import LEARNERS_DIR, RELEARNING_INTERVALS_DAYS, RELEARNING_SESSIONS_FOR_DURABLE
from src.edtech_core.curriculum import TOPIC_BY_ID


def _now() -> datetime:
    return datetime.now(timezone.utc)


def _iso(dt: datetime) -> str:
    return dt.isoformat(timespec="seconds")


@dataclass
class TopicMemory:
    attempts: int = 0
    correct: int = 0
    stage: int = 0                      # consecutive spaced successes on the interval ladder
    spaced_successes: int = 0
    last_reviewed: str | None = None
    due: str | None = None

    @property
    def current_interval_days(self) -> int:
        """Gap to the next review: 1 day after a miss/first success, then up the ladder."""
        return RELEARNING_INTERVALS_DAYS[min(max(self.stage - 1, 0), len(RELEARNING_INTERVALS_DAYS) - 1)]

    @property
    def error_rate(self) -> float:
        return 1 - self.correct / self.attempts if self.attempts else 0.5  # unseen = uncertain

    @property
    def durable(self) -> bool:
        return self.spaced_successes >= RELEARNING_SESSIONS_FOR_DURABLE

    def overdue_ratio(self, now: datetime) -> float:
        """>0 means due/overdue, scaled by the current interval (1.0 = one interval late)."""
        if not self.due:
            return 1.0  # covered but never quizzed → due now
        late_days = (now - datetime.fromisoformat(self.due)).total_seconds() / 86400
        return late_days / self.current_interval_days


@dataclass
class LearnerState:
    learner_id: str
    covered: list[str] = field(default_factory=list)        # topic ids, in order covered
    topics: dict[str, TopicMemory] = field(default_factory=dict)
    seen_problems: dict[str, str] = field(default_factory=dict)  # problem_id -> iso time
    quiz_ids: list[str] = field(default_factory=list)
    # Placement assessment result: {assessment_id, completed_at, levels{topic: gap|partial|solid}, placement}
    assessment: dict | None = None
    # Research Agent's plan built from the assessment: {created, steps:[{topic, start_stage, reason}]}
    learning_plan: dict | None = None
    # Worked-example / transfer progress per topic: {topic: {status, stage, transfer_passed, updated}}
    concept_progress: dict = field(default_factory=dict)
    # Peer-instruction log (calibration: confidence vs. correctness)
    peer_log: list = field(default_factory=list)

    @property
    def assessed(self) -> bool:
        return bool(self.assessment and self.assessment.get("completed_at"))

    # ------------------------------------------------------------------ persistence
    @staticmethod
    def _dir(learner_id: str):
        if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", learner_id):
            raise ValueError("learner_id must be 1-64 chars of letters, digits, _ . -")
        return LEARNERS_DIR / learner_id

    @classmethod
    def load(cls, learner_id: str) -> "LearnerState":
        path = cls._dir(learner_id) / "state.json"
        if not path.exists():
            return cls(learner_id=learner_id)
        raw = json.loads(path.read_text())
        raw["topics"] = {k: TopicMemory(**v) for k, v in raw.get("topics", {}).items()}
        return cls(**raw)

    def save(self) -> None:
        d = self._dir(self.learner_id)
        d.mkdir(parents=True, exist_ok=True)
        (d / "state.json").write_text(json.dumps(asdict(self), indent=2))

    def quiz_dir(self):
        return self._dir(self.learner_id) / "quizzes"

    # ------------------------------------------------------------------ coverage
    def cover(self, topic_id: str) -> None:
        if topic_id not in TOPIC_BY_ID:
            raise ValueError(f"unknown topic {topic_id!r}")
        if topic_id not in self.covered:
            self.covered.append(topic_id)
            self.topics.setdefault(topic_id, TopicMemory())

    @property
    def current_topic(self) -> str | None:
        return self.covered[-1] if self.covered else None

    # ------------------------------------------------------------------ results
    def apply_quiz_results(self, results: list[dict], when: datetime | None = None) -> dict[str, bool]:
        """results: [{problem_id, topic, correct: bool}] for one quiz session.
        Returns {topic: session_success} after updating the relearning schedule."""
        now = when or _now()
        by_topic: dict[str, list[bool]] = {}
        for r in results:
            by_topic.setdefault(r["topic"], []).append(bool(r["correct"]))
            if r.get("problem_id"):
                self.seen_problems[r["problem_id"]] = _iso(now)
        outcome = {}
        for topic, marks in by_topic.items():
            mem = self.topics.setdefault(topic, TopicMemory())
            mem.attempts += len(marks)
            mem.correct += sum(marks)
            success = all(marks)
            # Only a success at (or near) the due date counts as a *spaced* relearning
            # session; re-quizzing the same day must not fast-track a topic to "durable".
            spaced = mem.due is None or now >= datetime.fromisoformat(mem.due) - timedelta(
                days=0.25 * mem.current_interval_days)
            if success and spaced:
                mem.spaced_successes += 1
                mem.stage += 1
                mem.due = _iso(now + timedelta(days=mem.current_interval_days))
            elif not success:
                mem.stage = 0
                mem.due = _iso(now + timedelta(days=1))
            # success but early: schedule unchanged (still counts toward accuracy)
            mem.last_reviewed = _iso(now)
            outcome[topic] = success
        return outcome

    def summary(self) -> list[dict]:
        now = _now()
        rows = []
        for tid in self.covered:
            m = self.topics.get(tid, TopicMemory())
            rows.append({
                "topic": tid,
                "title": TOPIC_BY_ID[tid].title,
                "attempts": m.attempts,
                "accuracy": f"{m.correct / m.attempts:.0%}" if m.attempts else "—",
                "spaced_successes": m.spaced_successes,
                "status": "durable" if m.durable else ("due" if m.overdue_ratio(now) >= 0 else "scheduled"),
                "due": m.due or "now",
            })
        return rows