File size: 64,053 Bytes
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
756f8b1
 
cf9e1bd
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
"""The StepWise tutor: a topic-bound Claude tutor with per-idea levels and spaced review.

Design: syllabus/igcse/midterm/TUTOR_AGENT_PLAN.md in the project repo.

- Mastery: each student holds a level 0-4 on every atom (idea). Two correct answers in a
  row at or above the current level move it up one; a wrong answer moves it down one (two
  if the student said they were sure) and makes it due tomorrow. Self-check results feed
  the same levels.
- Sessions are typed and planned by the server (apps/selfcheck-space/TUTOR_STRUCTURE.md):
  learn <topic>, ask <topic>, fix <quiz attempt>, review <chapter>. Each has a fixed list of
  steps; Claude teaches one step at a time and calls finish_step to advance. Learn sessions on
  chunked topics run part by part with no turn limit (CHUNK_MODEL.md); the daily spend cap stays.
- Claude works only through five tools: get_student_state, record_attempt, calculate,
  finish_step, flag.
- Every message, tool call and level change is stored; parents read the full text.
"""
from __future__ import annotations

import ast
import json
import math
import operator
import threading
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path

import re
import time

# $ per million tokens. Cache writes use the 1-hour TTL (2x input), so a student who pauses
# for a few minutes does not pay to re-save the whole session.
CACHE = {"type": "ephemeral", "ttl": "1h"}
PRICES = {
    "claude-opus-5-5": {"in": 4.0, "out": 20.0, "write": 8.0, "read": 0.20, "label": "Opus 5.5"},
    "claude-fable-5-1": {"in": 10.0, "out": 50.0, "write": 20.0, "read": 0.25, "label": "Fable 5.1"},
}
# One effort level for the whole session: changing effort between turns discards the cached conversation.
SESSION_EFFORT = "medium"
OPUS, FABLE = "claude-opus-5-5", "claude-fable-5-1"
ROUTING_MODES = ("auto", "opus", "fable")
MAX_TOOL_ROUNDS = 6

HARD_WORDS = re.compile(
    r"\b(why|explain|don'?t (get|understand)|confus\w*|stuck|how come|prove|derive|what if|difference between|"
    r"compare|calculate|work out|show that|evaluate|discuss|plan an? (experiment|investigation))\b", re.I)
NUMBERY = re.compile(r"\d+(?:\.\d+)?")


def route(sess: dict, text, mode: str) -> tuple:
    """Pick (model, effort, reason) for one tutor turn.

    auto: quick turns (short answers, acknowledgements, simple recall) go to Opus 5.5 at low
    effort so they stay fast. Turns that need diagnosis or multi-step reasoning go to Fable 5.1:
    a why/explain/stuck message, a multi-step numeric answer, or a reply right after the
    student's last recorded answer was wrong.
    """
    if mode == "opus":
        return OPUS, "medium", "always Opus"
    if mode == "fable":
        return FABLE, "medium", "always Fable"
    if text is None:
        return OPUS, "medium", "session start"
    # Sticky upgrade: each model keeps its own prompt cache (the chapter text, ~20k tokens),
    # so once a session needs Fable it stays on Fable instead of paying to load both caches.
    if sess.get("upgraded"):
        return FABLE, "low" if len(text.split()) <= 12 else "medium", "session moved to Fable"
    reason = None
    if sess.get("lastResult") is False:
        reason = "last answer was wrong: diagnose"
    elif HARD_WORDS.search(text):
        reason = "asks why or multi-step"
    elif len(NUMBERY.findall(text)) >= 3 and len(text.split()) >= 8:
        reason = "multi-step working"
    if reason:
        sess["upgraded"] = True
        return FABLE, "medium", reason
    if len(text.split()) <= 12:
        return OPUS, "low", "short reply"
    return OPUS, "medium", "default"


def turn_cost(model: str, u) -> float:
    p = PRICES.get(model) or PRICES[OPUS]
    return ((u.input_tokens or 0) * p["in"] + (u.output_tokens or 0) * p["out"]
            + (getattr(u, "cache_creation_input_tokens", 0) or 0) * p["write"]
            + (getattr(u, "cache_read_input_tokens", 0) or 0) * p["read"]) / 1e6
INTERVAL_DAYS = {0: 0, 1: 1, 2: 2, 3: 4, 4: 7}
LEVEL_NAMES = {0: "not met", 1: "recall", 2: "apply one step", 3: "combine", 4: "exam-ready"}

HERE = Path(__file__).parent
CHAPTERS: dict[str, dict] = {
    json.loads(p.read_text(encoding="utf-8"))["id"]: json.loads(p.read_text(encoding="utf-8"))
    for p in sorted((HERE / "data" / "chapters").glob("*.json"))
}


TOPICS: dict[str, dict] = {}
for _p in sorted((HERE / "data" / "topics").glob("*.json")):
    _d = json.loads(_p.read_text(encoding="utf-8"))
    TOPICS[_d["chapterId"]] = _d
    if _d["chapterId"] in CHAPTERS:          # topic files carry the cleaned-up chapter title
        CHAPTERS[_d["chapterId"]]["chapter"] = _d["chapter"]

DAILY_CAP_USD = 5.0          # the only hard stop; there is no limit on turns (CHUNK_MODEL.md)
BREAK_AFTER_MIN = 20         # offer (never force) a break after this long on one part

# What Claude must do in each step. The server shows exactly one of these at a time.
STEPS = {
    "predict": ("Predict", "low", "First state the topic's big question in plain English (an everyday puzzle) and ask the student's guess at the whole answer; wait. When they reply, give our short intuitive answer to the whole puzzle in plain words, then question it as a curious student would ('but how do we know…?'), turning each doubt into a numbered smaller question, with no technical terms yet. Then ask ONE short prediction or intuition question about the first of them before any teaching (e.g. what do you think happens if…, why might…). Accept any honest attempt, react in one or two warm sentences, then call finish_step and move straight on to the next step."),
    "explain": ("Explain", "medium", "Teach the topic's core idea from first principles, building on what the student just predicted. Phenomenon first in plain words, then the problem that needs a word or tool, then the term. Use the listed paragraphs of the chapter text. Two to four short paragraphs, one everyday example, no new jargon without a meaning. End by asking whether it makes sense or if they want anything clarified. When they acknowledge (or after you answer one follow-up), call finish_step."),
    "check": ("Check", "low", "Ask two quick questions, ONE at a time, each on a different idea of this topic (recall or one-step). After each answer call record_attempt (level 1 or 2) and give one line of feedback; if wrong, give the right idea in one or two lines. After the second answer, call finish_step."),
    "apply": ("Apply", "medium", "Ask ONE exam-style question that needs two steps or combines two ideas of this topic (level 3). Use the hint ladder if they are stuck; never give the final answer first. When they reach an answer, call record_attempt, explain briefly, then call finish_step."),
    "wrapup": ("Wrap-up", "low", "Close the session: three short bullet points of what they practised and one thing to watch for. Praise effort specifically. Do NOT ask a new question. Call finish_step."),
    "diagnose": ("Your thinking", "medium", "Show the quiz question and the student's answer (given below). Ask them to explain how they got their answer. Do NOT reveal the correct answer yet. When they have explained, call finish_step."),
    "reteach": ("The idea", "medium", "From their explanation, name the exact faulty idea kindly. Re-teach only that idea in a few lines, with a quick case where the wrong belief gives an absurd result. Then give the correct answer to the quiz question with the reasoning. Call finish_step."),
    "retry": ("Try one", "low", "Give ONE new question testing the same idea with different numbers or context. When they answer, call record_attempt, give one line of feedback, and call finish_step."),
    "review_q": ("Review", "low", "Ask ONE quick question on the focus idea (it is due for review). After the answer call record_attempt; if wrong, explain the idea in two lines. Call finish_step."),
    "answer": ("Your question", "medium", "If the student has not asked yet, invite their question about this topic in one line and wait. When they ask, answer it clearly and briefly (under 150 words), grounded in the chapter text. If the question is outside this topic, say so in one line and offer the nearest thing in this topic. Then call finish_step."),
    "check1": ("Check", "low", "Ask ONE quick question that checks they understood your answer. After their answer call record_attempt, give one line of feedback, and call finish_step."),
    # Learning in parts ("chunks", syllabus/igcse/quizzes/CHUNK_MODEL.md). No turn limit in any of these.
    "c_predict": ("Predict", "low", "If this is part 1, the opening takes two exchanges. First message: state the topic's big question as an everyday puzzle in one or two plain-English sentences, and ask the student for their own guess at the WHOLE answer; then stop and wait. Second message (after they reply, even 'I don't know'): react warmly in one sentence; give our short intuitive answer to the whole puzzle in plain words (what is going on, no definitions or technical terms), building on their guess where you can; then question that answer as a curious student would ('but how do we know…?', 'who says…?', 'why would…?'), and show that each doubt is one of the smaller questions from the route given above, numbered and in order, in your own plain words. Then say we will settle them one at a time, starting with number 1. If this is a later part: in one or two sentences, recall the big question, say which numbered smaller question we have just answered and what it gave us, and why this next one is needed. Then ask this part's driving question (below), in your own words, as ONE question for the student to try before any teaching. Accept any honest attempt, including 'I don't know', warmly in one or two sentences, then call finish_step and go straight on to the next step in the same reply. (On part 1, only call finish_step after the student has answered this driving question, not after their guess at the big question.)"),
    "c_explain": ("Explain", "medium", "Teach ONLY this part's ideas (listed below), from first principles, starting from the driving question and what the student just said. One idea at a time, in this order: (a) what actually happens, in plain words, tied to something the student has seen; (b) the problem that creates, the reason we need a word or a tool for it ('to say exactly which way it bounces we need a fixed line to measure from'); (c) only then the term's name and meaning. For a living system, (b) is why the organism or system needs it. Use no technical term outside this part's new terms and words the student already knows. Keep each message short (under about 150 words) and end it with a quick question that checks they are following. If they say it doesn't make sense, rebuild from a simpler starting point and an everyday example; never just repeat. There is no limit on exchanges: take as many as they need. When they have followed every idea in this part, call finish_step."),
    "c_check": ("Check", "low", "Make sure every idea in this part has landed, in as few questions as possible (usually two to four). Ask ONE question at a time, each on an idea not yet answered right (listed below as 'still to check'); never ask about an idea already answered right. Combine two of this part's ideas in one question where you can. After each answer call record_attempt with the atom ids it tested (level 1 or 2) and give one line of feedback. If it was wrong, re-explain that idea a fresh way in two to four lines, then ask a new question on it. When every idea has been answered right, call finish_step."),
}
CHUNK_STEPS = ("c_predict", "c_explain", "c_check")


def chapter_of(set_or_chapter_id: str) -> str:
    """Quiz ids look like <chapterId>_qNN; anything else is already a chapter id."""
    import re as _re
    return _re.sub(r"_q\d{2}$", "", set_or_chapter_id)


def topic_of(chapter_id: str, topic_id: str | None) -> dict | None:
    for t in (TOPICS.get(chapter_id) or {}).get("topics", []):
        if t["id"] == topic_id:
            return t
    return None


def chunk_key(chapter_id: str, chunk_id: str) -> str:
    return f"{chapter_id}/{chunk_id}"


def chunk_of(sess: dict, chunk_id: str | None) -> dict | None:
    t = topic_of(sess["chapterId"], sess.get("topicId"))
    return next((c for c in (t or {}).get("chunks", []) if c["id"] == chunk_id), None)


def chunk_status(progress: dict, chapter_id: str, chunk_id: str) -> str:
    """'learned', 'skipped' or 'todo' for one student."""
    return (progress.get("chunks", {}).get(chunk_key(chapter_id, chunk_id)) or {}).get("status", "todo")


def chunk_plan(chapter_id: str, topic: dict, progress: dict, start_id: str | None) -> list[str]:
    """Which parts a Learn session covers: from the start part (asked for, else the first not yet
    learned, else the first) to the end of the topic, skipping later parts already learned."""
    ids = [c["id"] for c in topic["chunks"]]
    todo = [c for c in ids if chunk_status(progress, chapter_id, c) != "learned"]
    start = start_id if start_id in ids else (todo[0] if todo else ids[0])
    i = ids.index(start)
    return [start] + [c for c in ids[i + 1:] if c in todo]


def build_plan(kind: str, chapter_id: str, m: dict, topic: dict | None, fix_items: list | None,
               progress: dict | None = None, chunk_id: str | None = None) -> tuple[str, list]:
    """Return (goal, steps). Each step: {name, label, focus[atom ids], context, status}."""
    def step(name, focus=(), context="", chunk=None):
        label, _, _ = STEPS[name]
        return {"name": name, "label": label, "focus": list(focus), "context": context, "status": "todo", "exchanges": 0,
                **({"chunk": chunk} if chunk else {})}
    chapter = CHAPTERS[chapter_id]
    if kind == "learn" and topic and topic.get("chunks"):
        by = {c["id"]: c for c in topic["chunks"]}
        steps = [step(n, by[cid]["atom_ids"], chunk=cid) for cid in chunk_plan(chapter_id, topic, progress or {}, chunk_id)
                 for n in CHUNK_STEPS]
        return (f"Learn: {topic['title']}. {topic['goal']}", steps)
    if kind == "learn":
        ids = topic["atom_ids"]
        return (f"Learn: {topic['title']}. {topic['goal']}",
                [step("predict", ids), step("explain", ids), step("check", ids), step("apply", ids), step("wrapup", ids)])
    if kind == "ask":
        ids = topic["atom_ids"]
        return (f"Ask about: {topic['title']}", [step("answer", ids), step("check1", ids), step("wrapup", ids)])
    if kind == "fix":
        steps = []
        for it in (fix_items or [])[:3]:
            ctx = (f"Quiz question: {it['prompt']}\n" + (f"Options: {' | '.join(f'{chr(65 + i)}. {o}' for i, o in enumerate(it['options']))}\n" if it.get("options") else "")
                   + f"Student's answer: {it['response']}\nCorrect answer (do not reveal before the 'The idea' step): {it['correct']}\n"
                   + f"Mark scheme: {it.get('mark_scheme', '')}")
            steps += [step("diagnose", it["atom_ids"], ctx), step("reteach", it["atom_ids"], ctx), step("retry", it["atom_ids"])]
        steps.append(step("wrapup", [a for it in (fix_items or [])[:3] for a in it["atom_ids"]]))
        n = min(3, len(fix_items or []))
        return (f"Fix {n} mistake{'s' if n != 1 else ''} from your quiz", steps)
    if kind == "review":
        t = now()
        ids = {a["id"] for a in chapter["atoms"]}
        due = sorted([aid for aid, st in m.items() if aid in ids and st.get("level", 0) > 0 and st.get("due")
                      and datetime.fromisoformat(st["due"]) <= t], key=lambda aid: (m[aid]["level"], m[aid]["due"]))
        if len(due) < 5:  # top up with the weakest ideas already met
            due += [aid for aid, st in sorted(m.items(), key=lambda kv: kv[1].get("level", 0))
                    if aid in ids and st.get("seen") and aid not in due][: 5 - len(due)]
        due = due[:5]
        return (f"Review: {chapter['chapter']}", [step("review_q", [a]) for a in due] + [step("wrapup", due)])
    raise ValueError(kind)


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


def iso(d: datetime) -> str:
    return d.isoformat(timespec="seconds")


# ---------------------------------------------------------------- mastery
def blank_atom() -> dict:
    return {"level": 0, "streak": 0, "seen": 0, "right": 0, "last": None, "due": None}


def apply_result(m: dict, atom_id: str, correct: bool, level_tested: int, confidence: str | None, source: str) -> dict:
    a = m.setdefault(atom_id, blank_atom())
    before = a["level"]
    a["seen"] += 1
    a["last"] = iso(now())
    if correct:
        a["right"] += 1
        if level_tested >= a["level"]:
            a["streak"] += 1
            if a["level"] == 0:
                a["level"], a["streak"] = 1, 0          # first correct answer: met it
            elif a["streak"] >= 2:
                a["level"], a["streak"] = min(4, a["level"] + 1), 0
        a["due"] = iso(now() + timedelta(days=INTERVAL_DAYS[a["level"]]))
    else:
        drop = 2 if confidence == "sure" else 1
        a["level"] = max(0, a["level"] - drop)
        a["streak"] = 0
        a["due"] = iso(now() + timedelta(days=1))
    a.setdefault("log", []).append({"t": a["last"], "ok": correct, "lv": level_tested, "conf": confidence, "src": source})
    a["log"] = a["log"][-15:]
    return {"atom": atom_id, "from": before, "to": a["level"]}


def apply_selfcheck(m: dict, set_id: str, attempt: dict) -> None:
    """A self-check answer counts as a level-2 test of each atom it covers."""
    for atom_id, (got, mx) in attempt.get("atoms", {}).items():
        if mx:
            apply_result(m, atom_id, got / mx >= 0.8, 2, None, f"selfcheck:{set_id}")


def plan(m: dict, chapter: dict, reviews: int = 5, new: int = 2) -> dict:
    t = now()
    levels = {a["id"]: m.get(a["id"], blank_atom())["level"] for a in chapter["atoms"]}
    due = [aid for aid, st in m.items() if aid in levels and st.get("due") and st["level"] > 0
           and datetime.fromisoformat(st["due"]) <= t]
    due.sort(key=lambda aid: (m[aid]["level"], m[aid]["due"]))
    ready = [a["id"] for a in chapter["atoms"] if levels[a["id"]] == 0
             and all(levels.get(p, 0) >= 2 for p in a["prerequisites"])]
    return {"reviews": due[:reviews], "new": ready[:new]}


# ---------------------------------------------------------------- tools
TOOLS = [
    {
        "name": "get_student_state",
        "description": "Get this student's current level (0-4) on every idea in this chapter, which ideas are due for review, recent results and their latest quiz in this chapter (its score, and each question they lost marks on with their answer and the right answer). Call it at the start of a session and whenever you need to choose what to ask next.",
        "input_schema": {"type": "object", "properties": {}, "additionalProperties": False},
    },
    {
        "name": "record_attempt",
        "description": "Record the student's answer to a question you asked, so their idea levels update. Call it once for every question the student actually attempts, after you have judged the answer, before you reply.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {
                "atom_ids": {"type": "array", "items": {"type": "string"}, "description": "1-4 atom ids the question tested, from this chapter's list."},
                "correct": {"type": "boolean", "description": "True only if the answer AND the reasoning were right. A right answer with a wrong reason is false."},
                "level_tested": {"type": "integer", "enum": [1, 2, 3, 4], "description": "1 recall, 2 apply one step, 3 combine ideas, 4 exam-style unfamiliar or multi-part."},
                "misconception_id": {"type": ["string", "null"], "description": "Misconception id if the wrong answer matches one, else null."},
                "question": {"type": "string", "description": "The question, in under 25 words."},
                "student_answer": {"type": "string", "description": "The student's answer, in under 25 words."},
            },
            "required": ["atom_ids", "correct", "level_tested", "misconception_id", "question", "student_answer"],
            "additionalProperties": False,
        },
    },
    {
        "name": "calculate",
        "description": "Evaluate an arithmetic expression exactly as written and return the number. Use it to check every numerical answer before you tell the student it is right or wrong. Supports + - * / ** ( ), sqrt(), log10(), and numbers like 6.02e23.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {"expression": {"type": "string"}},
            "required": ["expression"],
            "additionalProperties": False,
        },
    },
    {
        "name": "finish_step",
        "description": "Call when the CURRENT step's goal (shown in the latest session note) is met. The server then moves to the next step and returns its instructions, which you should follow straight away in the same reply. When the last step is finished the session is complete.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {
                "outcome": {"type": "string", "enum": ["done", "skipped"], "description": "done if the goal was met; skipped if the student wanted to move on or could not engage."},
                "note": {"type": "string", "description": "One short line for the parent about how this step went."},
            },
            "required": ["outcome", "note"],
            "additionalProperties": False,
        },
    },
    {
        "name": "flag",
        "description": "Flag something the parent should see: off_topic (student keeps pulling away from the subject), answer_seeking (student asks you to just give answers to homework or a test), distress (student says something upsetting or personal), other.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {
                "kind": {"type": "string", "enum": ["off_topic", "answer_seeking", "distress", "other"]},
                "note": {"type": "string", "description": "One sentence for the parent."},
            },
            "required": ["kind", "note"],
            "additionalProperties": False,
        },
    },
]

_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
        ast.Pow: operator.pow, ast.USub: operator.neg, ast.UAdd: operator.pos}
_FUNCS = {"sqrt": math.sqrt, "log10": math.log10, "ln": math.log, "abs": abs, "round": round}


def safe_eval(expr: str) -> float:
    def ev(n):
        if isinstance(n, ast.Expression):
            return ev(n.body)
        if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)):
            return n.value
        if isinstance(n, ast.BinOp) and type(n.op) in _OPS:
            if isinstance(n.op, ast.Pow) and abs(ev(n.right)) > 400:
                raise ValueError("exponent too large")
            return _OPS[type(n.op)](ev(n.left), ev(n.right))
        if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS:
            return _OPS[type(n.op)](ev(n.operand))
        if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in _FUNCS and not n.keywords:
            return _FUNCS[n.func.id](*[ev(a) for a in n.args])
        raise ValueError("only numbers, + - * / ** ( ) and sqrt/log10/ln/abs/round are allowed")
    cleaned = expr.replace("×", "*").replace("^", "**").replace("−", "-")
    return ev(ast.parse(cleaned, mode="eval"))


# ---------------------------------------------------------------- prompts
RULES = """You are the StepWise tutor for a Cambridge IGCSE student (about 15 years old). You tutor ONE chapter, given below. Your job is to make the student's understanding visible and fix it, and to test them in small, increasing steps. You are not an answer machine.

How you teach
- One question at a time. Ask, then wait for the student's answer. Keep each message short (usually under 120 words); longer only when explaining an idea from first principles.
- Before explaining something new, ask the student to predict or try first.
- Big question first, intuitive answer next, smaller questions from questioning that answer. Every topic answers one big question or everyday puzzle (e.g. "how does a mirror let you see yourself?", "why does a straw look bent in water?"). Open a topic in this order: (1) state the puzzle in plain English; (2) ask the student for their own guess at the WHOLE answer and wait; (3) react warmly, then give our short, intuitive answer to the whole puzzle in plain words, building on their guess where you can (a story of what is going on, not definitions); (4) then question that answer the way a curious student would ("but how do we know light bounces like that?", "who says it comes back at the same angle?", "why would your eyes be fooled?"), and show that each of these doubts is one smaller question, numbered in order, so the smaller questions grow out of the answer rather than being announced as a list; (5) then start on smaller question 1. As you move along, say where you are on the route and why the next small question is needed for the big one.
- Phenomenon before jargon. First describe what actually happens, in plain words and with something the student has seen. Only when they have the picture, show the problem a technical word or tool solves ("to say exactly which way the light bounces we need something fixed to measure from"), and only then give its name and definition. Never introduce a term just because it comes next in the syllabus.
- When they are stuck, use the hint ladder: (1) name the idea, (2) name the first step, (3) show the first step, (4) a worked example with DIFFERENT numbers, then they redo the original. Never give the final answer first.
- Asking why: if the question itself asked for a reason, a right answer needs a reason. Otherwise a right recall or one-step answer counts as right; do not hold back credit to demand a reason. Ask "why?" at most ONCE per question; if the reason is thin or missing, give the one-line reason yourself, count the answer, and move on.
- Stay on the route. Teach and test only the ideas listed for the current part. No side trips, extra traps, extensions, "one more thing" or bonus questions beyond those ideas, however interesting. If a side point is truly needed to follow the part, give it in one sentence and carry on.
- If the student says they are finding it hard to answer, or asks you to ask again, don't repeat the question word for word: ask the same thing more simply, in fewer words, with a small hint or an everyday example, or split it into a smaller first question. If they ask for a hint, give one hint, not the answer.
- If the student asks about their quiz mistakes, call get_student_state and use latest_selfcheck.missed: you can see each question they lost marks on, their answer and the right answer. Never say you can't see the quiz. Take one missed question at a time: show it, ask what they were thinking, then explain the idea briefly and give the right answer. When they are done, come back to the current step.
- Read the student. Short or tired replies ("IDK", "Because.", "just tell me", one-word answers) or annoyance ("I already told you") mean stop probing: give the answer plainly in a few lines, check it with ONE easy question, and move on. If they show they already know something (they say so, or answer it fully), skip ahead to what is still left; never make them repeat it.
- Feeling buttons. A message starting [feeling lost] means the student pressed "Feeling lost": stop, say in one line where we are and what we are trying to find out, then rebuild the current idea from a simpler starting point with an everyday example, in short steps, and ask one easy question. A message starting [feeling repetitive] means "Feeling repetitive": briefly acknowledge it, do not re-ask anything already answered right, and move straight on to the next idea not yet covered (or finish the step if none is left).
- When a wrong answer matches a listed misconception, name it kindly, show a quick case where the wrong belief gives an absurd result, then ask a fresh question on the same idea.
- Ground every explanation in the chapter text below (you may cite paragraph ids like [P5] for yourself, but explain in plain words). If something is outside this chapter, say so briefly and offer to come back to the chapter.
- Check every number with the calculate tool before saying an answer is right or wrong. Never do arithmetic in your head.
- When you number things for the student (smaller questions, steps), write the label in plain text at the start of the line, e.g. 'Question 1:', 'Question 2:', 'Step 3:', and keep any reason on the SAME line after a dash. Never use list syntax like '1.' on its own line followed by other lines, because the chat then shows every item as 1.
- Use British spelling and IGCSE terms. Write chemistry and physics with Unicode (H₂O, 6.02 × 10²³, m/s²). Plain text with short lines; no tables, no headings, no LaTeX.

Levels (each idea, per student): 0 not met, 1 recall, 2 apply one step, 3 combine with other ideas, 4 exam-ready. Pitch questions at the student's current level or one above. Only introduce an idea when its prerequisites are at level 2. Combination questions may only use ideas the student already holds at level 2 or above.

Sessions and steps: every session has a goal and a fixed list of steps chosen by the app. A session note tells you the current step, what to do in it, and the focus ideas. Do only the current step; when its goal is met call finish_step and then follow the next step's instructions in the same reply. Do not name the steps to the student unless it helps ("Now a quick check…"). There is no limit on exchanges: move on when the step's goal is met, not before. If the student asks something off the plan but on this chapter, answer briefly and return to the step.

Parts: a Learn session may be split into parts, each answering one driving question with a few ideas. Teach only the current part's ideas; never front-load names of structures or terms from later parts. If the student asks about a later part's idea, say in one line that it is coming in a later part, then carry on.

Recording: after judging every attempted answer, call record_attempt with the atom ids it tested, before you reply. The student may tag a message with [confidence: guess|think so|sure]; that is attached automatically.

Boundaries
- Stay on this chapter, its subject's exam technique, and study skills. Redirect anything else in one friendly sentence. If they keep pulling away, call flag with off_topic.
- If they ask you to just give answers to homework, a test or a self-check, decline kindly, offer to work through the idea on a different example, and call flag with answer_seeking.
- If they say anything distressing or personal (feeling unsafe, very upset, self-harm, bullying), respond with warmth, do not counsel, suggest talking to a parent or a teacher they trust, and call flag with distress.
- The student knows their parent can read these chats. Be warm, encouraging and honest. Praise effort and good reasoning, not just right answers."""


PARA_ID = re.compile(r"P\d+[a-z]?")                 # e.g. P15 or an inserted P15b
PARA_START = re.compile(r"^\s*\[(P\d+[a-z]?)\]")


def session_scope(chapter: dict, topic: dict | None, steps: list) -> dict | None:
    """The atoms and paragraphs one session needs: its topic, focus and part ideas plus every prerequisite.

    The system prompt then carries only that slice of the chapter (cost: it is re-read every turn).
    None means the whole chapter (the slice would be nearly all of it anyway).
    """
    by_id = {a["id"]: a for a in chapter["atoms"]}
    want = set(topic["atom_ids"]) if topic else set()
    for st in steps:
        want.update(st.get("focus") or [])
    if topic:
        for ch in topic.get("chunks") or []:
            want.update(ch.get("atom_ids") or [])
    todo = list(want)
    while todo:                                   # close over prerequisites
        a = by_id.get(todo.pop())
        for p in (a or {}).get("prerequisites") or []:
            if p not in want:
                want.add(p)
                todo.append(p)
    want &= set(by_id)
    if not want or len(want) >= 0.8 * len(by_id):
        return None
    paras = set(PARA_ID.findall(" ".join(by_id[a]["paragraphs"] for a in want)))
    if topic:
        paras.update(topic.get("paragraphs") or [])
    return {"atoms": sorted(want), "paragraphs": sorted(paras, key=lambda p: (int(re.sub(r"\D", "", p)), p))}


def chapter_excerpt(text: str, paras: set) -> str:
    """Keep only the [Pn] blocks in paras (a block runs to the next [P..] or heading), with their headings."""
    out, heading, keep, shown = [], None, False, set()
    for line in text.splitlines():
        if line.startswith("#"):
            heading, keep = line, False
            continue
        m = PARA_START.match(line)
        if m:
            keep = m.group(1) in paras
            if keep and heading and heading not in shown:
                out += ["", heading]
                shown.add(heading)
        if keep:
            out.append(line)
    return "\n".join(out).strip()


def system_blocks(chapter: dict, scope: dict | None = None) -> list[dict]:
    keep = set(scope["atoms"]) if scope else None
    atoms = "\n".join(
        f"{a['id']} [{a['type']}, {a['tier']}, {a['paragraphs']}] {a['statement']} | why: {a['why']}"
        + (f" | needs: {', '.join(a['prerequisites'])}" if a["prerequisites"] else "")
        for a in chapter["atoms"] if keep is None or a["id"] in keep)
    mis = "\n".join(f"{m['id']}: wrong belief: {m['wrong']} | correct: {m['correct']} | fix with: {', '.join(m['atoms'])}"
                    for m in chapter["misconceptions"] if keep is None or keep & set(m["atoms"]))
    if scope:
        body = chapter_excerpt(chapter["text"], set(scope["paragraphs"]))
        label = ("Chapter text: only the paragraphs this session needs. If the student asks about another part of "
                 "this chapter, answer in a line or two and say it is covered in another topic")
    else:
        body, label = chapter["text"], "Chapter text (canonical, from first principles)"
    text = (f"{RULES}\n\n=== CHAPTER: {chapter['subject']} {chapter['code']}, {chapter['chapter']} ===\n\n"
            f"--- {label} ---\n{body}\n\n"
            f"--- Ideas (atoms) ---\n{atoms}\n\n--- Known misconceptions ---\n{mis}\n")
    return [{"type": "text", "text": text, "cache_control": CACHE}]


# ---------------------------------------------------------------- sessions
def current_step(sess: dict) -> dict | None:
    return next((st for st in sess.get("plan", []) if st["status"] == "todo"), None)


def session_chunks(sess: dict) -> list[str]:
    out = []
    for st in sess.get("plan", []):
        if st.get("chunk") and st["chunk"] not in out:
            out.append(st["chunk"])
    return out


def still_to_check(sess: dict, chunk_id: str) -> list[str]:
    ch = chunk_of(sess, chunk_id) or {"atom_ids": []}
    right = set(sess.get("chunkRight", {}).get(chunk_id, []))
    return [a for a in ch["atom_ids"] if a not in right]


def step_note(sess: dict, st: dict) -> str:
    chapter = CHAPTERS[sess["chapterId"]]
    names = {a["id"]: a["statement"] for a in chapter["atoms"]}
    mis = {m["id"]: m for m in chapter["misconceptions"]}
    ctx = f"\nContext:\n{st['context']}" if st.get("context") else ""
    if st.get("chunk"):
        ch = chunk_of(sess, st["chunk"]) or {}
        parts = session_chunks(sess)
        k = parts.index(st["chunk"]) + 1
        steps = [s for s in sess["plan"] if s.get("chunk") == st["chunk"]]
        focus = "\n".join(f"- {a}: {names.get(a, '')}" for a in ch.get("atom_ids", []))
        extra = ""
        if ch.get("new_terms"):
            extra += f"\nNew terms allowed in this part: {', '.join(ch['new_terms'])}"
        if ch.get("paragraphs"):
            extra += f"\nChapter paragraphs: {', '.join(ch['paragraphs'])}"
        if ch.get("misconceptions"):
            extra += "\nWatch for: " + "; ".join(f"{m} ({mis[m]['wrong']})" for m in ch["misconceptions"] if m in mis)
        done_before = [c for c in parts[:k - 1]]
        if done_before:
            extra += f"\nEarlier parts already learned this session: {', '.join((chunk_of(sess, c) or {}).get('title', c) for c in done_before)}"
        prior = sess.get("prior")
        if prior and k == 1 and st["name"] == "c_predict":
            done = f" Parts already learnt: {', '.join(prior['learnt'])}." if prior.get("learnt") else ""
            extra += (f"\nThis student has already started this topic in {prior['sessions']} earlier session(s), last on {prior['last']}.{done} "
                      "They have heard the big question and our intuitive answer. Do NOT ask for their guess at the big question again "
                      "and do NOT repeat the intuitive answer: treat this as a later part (recall the big question and where we are in one or two sentences).")
        if st["name"] == "c_check":
            left = still_to_check(sess, st["chunk"])
            extra += "\nStill to check: " + (", ".join(left) if left else "none: call finish_step")
        started = sess.get("chunkStarted", {}).get(st["chunk"])
        if started and not sess.get("breakOffered", {}).get(st["chunk"]) \
                and now() - datetime.fromisoformat(started) > timedelta(minutes=BREAK_AFTER_MIN):
            sess.setdefault("breakOffered", {})[st["chunk"]] = True
            extra += ("\nThey have been on this part for over 20 minutes. Once, kindly, offer a short break "
                      "(they can stop and carry on later from this part, or keep going). Do not end the session yourself.")
        route = "\n".join(f"  {n}. {(chunk_of(sess, c) or {}).get('question', '')}" + ("   <- this part" if n == k else "")
                          for n, c in enumerate(parts, 1))
        t = topic_of(sess["chapterId"], sess.get("topicId")) if sess.get("topicId") else None
        big = f"\nTopic: {t.get('title', '')}. Topic goal (turn it into ONE plain-English big question or everyday puzzle; do not quote it): {t.get('goal', '')}" if t else ""
        return (f"SESSION GOAL: {sess['goal']}{big}\nRoute through the topic (each part answers one smaller question on the way to the big one):\n{route}\n"
                f"PART {k} of {len(parts)}: {ch.get('title', '')}\n"
                f"Driving question: {ch.get('question', '')}\n"
                f"CURRENT STEP {steps.index(st) + 1} of {len(steps)} in this part: {STEPS[st['name']][0]}\n"
                f"What to do: {STEPS[st['name']][2]}\nThis part's ideas (teach and check only these):\n{focus}{extra}{ctx}")
    idx = sess["plan"].index(st) + 1
    focus = "\n".join(f"- {a}: {names.get(a, '')}" for a in st["focus"][:12])
    paras = ""
    if sess.get("topicId"):
        t = topic_of(sess["chapterId"], sess["topicId"])
        if t and t.get("paragraphs"):
            paras = f"\nChapter paragraphs for this topic: {', '.join(t['paragraphs'])}"
    return (f"SESSION GOAL: {sess['goal']}\nCURRENT STEP {idx} of {len(sess['plan'])}: {STEPS[st['name']][0]}\n"
            f"What to do: {STEPS[st['name']][2]}\nFocus ideas:\n{focus}{paras}{ctx}")


def spent_today(store, student_id: str) -> float:
    """Tutor replies plus Report coach replies today, for the daily cap."""
    today = now().date().isoformat()
    talks = list(store.chats.values()) + list(getattr(store, "coach", {}).values())
    return sum(m.get("cost") or 0 for s in talks if s["studentId"] == student_id
               for m in s["transcript"] if m.get("role") in ("tutor", "coach") and str(m.get("t", "")).startswith(today))


class CapReached(Exception):
    pass


def _meta(sess: dict) -> dict:
    last = sess["transcript"][-1]
    return {k: last.get(k) for k in ("model", "effort", "why", "seconds", "cost")}


class Tutor:
    def __init__(self, store, students: dict, client_factory) -> None:
        self.store = store              # app.Store: .mastery, .chats, queue_write()
        self.students = students
        self.client_factory = client_factory
        self.locks: dict[str, threading.Lock] = {}
        self.quiz_mistakes = lambda attempt: []     # set by app.py (it knows the quiz questions)
        self.quiz_title = lambda set_id: set_id

    def _lock(self, sid: str) -> threading.Lock:
        return self.locks.setdefault(sid, threading.Lock())

    def state_for(self, student_id: str, chapter: dict) -> dict:
        m = self.store.mastery.get(student_id, {})
        t = now()
        out = []
        for a in chapter["atoms"]:
            st = m.get(a["id"], blank_atom())
            out.append({"id": a["id"], "level": st["level"], "seen": st["seen"], "right": st["right"],
                        "due": bool(st.get("due") and datetime.fromisoformat(st["due"]) <= t and st["level"] > 0)})
        last = [x for x in self.store.attempts if x["studentId"] == student_id and chapter_of(x["setId"]) == chapter["id"]]
        last.sort(key=lambda x: x.get("submittedAt") or "")
        latest = "none yet"
        if last:
            a = last[-1]
            latest = {"quiz": self.quiz_title(a["setId"]), "score": f"{a['score']:g}/{a['max']:g}", "submitted": a.get("submittedAt"),
                      "missed": [{k: it[k] for k in ("prompt", "options", "response", "correct", "atom_ids") if it.get(k)}
                                 for it in self.quiz_mistakes(a)][:6]}
        return {"ideas": out, "due_plan": plan(m, chapter), "latest_selfcheck": latest}

    def _run_tool(self, sess: dict, name: str, args: dict) -> str:
        chapter = CHAPTERS[sess["setId"]]
        if name == "get_student_state":
            return json.dumps(self.state_for(sess["studentId"], chapter))
        if name == "calculate":
            try:
                v = safe_eval(args["expression"])
                return json.dumps({"value": v, "rounded_3sf": float(f"{v:.3g}")})
            except Exception as e:  # noqa: BLE001 - report any evaluation problem to the model
                return json.dumps({"error": str(e)})
        if name == "record_attempt":
            valid = {a["id"] for a in chapter["atoms"]}
            ids = [a for a in args.get("atom_ids", []) if a in valid][:4]
            if not ids:
                return json.dumps({"error": "none of those atom ids are in this chapter"})
            m = self.store.mastery.setdefault(sess["studentId"], {})
            changes = [apply_result(m, a, bool(args["correct"]), int(args["level_tested"]), sess.get("confidence"), f"tutor:{sess['id']}")
                       for a in ids]
            cur = current_step(sess)
            if cur and cur.get("chunk"):         # live idea status for the part being learnt
                own = set((chunk_of(sess, cur["chunk"]) or {}).get("atom_ids", []))
                tried = sess.setdefault("chunkTried", {}).setdefault(cur["chunk"], [])
                tried += [a for a in ids if a in own and a not in tried]
                if args["correct"]:
                    # Only a right answer in the Check step (after all the teaching) counts towards learning
                    # the part; right answers while it is being explained show as "following".
                    key = "chunkRight" if cur["name"] == "c_check" else "chunkFollowing"
                    right = sess.setdefault(key, {}).setdefault(cur["chunk"], [])
                    right += [a for a in ids if a in own and a not in right]
            sess["attempts"].append({"t": iso(now()), **args, "confidence": sess.get("confidence"), "changes": changes})
            sess["lastResult"] = bool(args["correct"])
            self.store.queue_write(f"mastery/{sess['studentId']}.json", m)
            out = {"recorded": True, "level_changes": changes}
            if cur and cur["name"] == "c_check":
                out["still_to_check"] = still_to_check(sess, cur["chunk"])
            return json.dumps(out)
        if name == "finish_step":
            cur = current_step(sess)
            if cur is None:
                return json.dumps({"session_complete": True, "instruction": "The session is complete. Say a short goodbye; do not ask a new question."})
            skipped = args.get("outcome") == "skipped"
            if cur["name"] == "c_check" and not skipped and still_to_check(sess, cur["chunk"]):
                left = still_to_check(sess, cur["chunk"])
                return json.dumps({"not_yet": True, "still_to_check": left, "instruction":
                                   "Not every idea in this part has been answered right yet. Ask ONE question on the next idea "
                                   "still to check (re-explain it briefly first if they got it wrong), record it, and call finish_step "
                                   "again once all are right. Use outcome 'skipped' only if the student asks to move on."})
            cur["status"] = "skipped" if skipped else "done"
            cur["note"] = args.get("note", "")
            if cur.get("chunk") and (cur["name"] == "c_check" or skipped):
                # a skipped step skips the rest of its part
                for st in sess["plan"]:
                    if st.get("chunk") == cur["chunk"] and st["status"] == "todo":
                        st["status"] = "skipped"
                self._chunk_finished(sess, cur["chunk"], "skipped" if skipped else "learned")
                nxt = current_step(sess)
                if nxt is None:
                    sess["complete"] = True
                    sess["summary"] = self.summary(sess)
                    return json.dumps({"session_complete": True, "instruction":
                                       "That was the last part of this topic. In three short bullet points say what they now understand, "
                                       "praise one specific thing they did well, and do NOT ask a new question. The app shows the summary and quizzes."})
                return json.dumps({"part_finished": True, "instruction":
                                   "This part is finished. In two or three short lines tell the student what they now understand from it "
                                   "and praise one specific thing. Do NOT ask a question and do NOT start the next part: the app now shows "
                                   "them a card to take this part's short quiz or carry on. The next part starts when they reply."})
            nxt = current_step(sess)
            if nxt is None:
                sess["complete"] = True
                sess["summary"] = self.summary(sess)
                return json.dumps({"session_complete": True, "instruction": "That was the last step. Finish your message warmly in one line; the app shows the summary."})
            if nxt.get("chunk"):
                sess.setdefault("chunkStarted", {}).setdefault(nxt["chunk"], iso(now()))
            return json.dumps({"next_step": nxt["label"], "instruction": step_note(sess, nxt)})
        if name == "flag":
            sess["flags"].append({"t": iso(now()), **args})
            return json.dumps({"flagged": True})
        return json.dumps({"error": f"unknown tool {name}"})

    def _turn(self, sess: dict, model: str, effort: str, reason: str) -> str:
        import anthropic

        client = self.client_factory()
        chapter = CHAPTERS[sess["setId"]]
        replies, t0, cost, served = [], time.monotonic(), 0.0, model
        for _ in range(MAX_TOOL_ROUNDS):
            try:
                resp = client.beta.messages.create(
                    model=model,
                    max_tokens=16000,
                    betas=["server-side-fallback-2026-07-01"],
                    fallbacks="default",
                    output_config={"effort": effort},
                    cache_control=CACHE,   # also cache the growing conversation
                    system=system_blocks(chapter, sess.get("scope")),
                    tools=TOOLS,
                    messages=sess["messages"],
                )
            except anthropic.BadRequestError:
                if model == FABLE:   # e.g. Fable not enabled for this account: use Opus for this turn
                    sess["flags"].append({"t": iso(now()), "kind": "other", "note": "A Fable 5.1 request was rejected; Opus 5.5 answered instead."})
                    model, effort, reason = OPUS, "medium", reason + " (Fable unavailable)"
                    continue
                raise
            served = getattr(resp, "model", None) or model
            u = resp.usage
            c = turn_cost(served, u)
            cost += c
            bm = sess["usage"].setdefault("byModel", {}).setdefault(
                served, {"turns": 0, "input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "cost": 0.0})
            parts = {"input": u.input_tokens or 0, "output": u.output_tokens or 0,
                     "cache_read": getattr(u, "cache_read_input_tokens", 0) or 0,
                     "cache_write": getattr(u, "cache_creation_input_tokens", 0) or 0}
            for k, v in parts.items():
                bm[k] += v
                sess["usage"][k] = sess["usage"].get(k, 0) + v
            bm["cost"] = round(bm["cost"] + c, 6)
            sess["messages"].append({"role": "assistant", "content": [blk.to_dict() for blk in resp.content]})
            text = "\n".join(blk.text for blk in resp.content if blk.type == "text").strip()
            if text:
                replies.append(text)
            if resp.stop_reason == "refusal":
                replies.append(f"I can't help with that one. Let's get back to {chapter['chapter']}.")
                sess["flags"].append({"t": iso(now()), "kind": "other", "note": "The model declined a message."})
                break
            if resp.stop_reason != "tool_use":
                break
            results = []
            for blk in resp.content:
                if blk.type == "tool_use":
                    out = self._run_tool(sess, blk.name, blk.input or {})
                    sess["tools"].append({"t": iso(now()), "name": blk.name, "input": blk.input, "output": out})
                    results.append({"type": "tool_result", "tool_use_id": blk.id, "content": out})
            sess["messages"].append({"role": "user", "content": results})
        sess["usage"].setdefault("byModel", {}).setdefault(
            served, {"turns": 0, "input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "cost": 0.0})["turns"] += 1
        sess["usage"]["cost"] = round(sess["usage"].get("cost", 0.0) + cost, 6)
        reply = "\n\n".join(replies) or "Sorry, I lost my train of thought. Could you say that again?"
        sess["transcript"].append({"role": "tutor", "text": reply, "t": iso(now()), "model": served, "effort": effort,
                                   "why": reason, "seconds": round(time.monotonic() - t0, 1), "cost": round(cost, 5)})
        return reply

    def _chunk_finished(self, sess: dict, chunk_id: str, status: str) -> None:
        ch = chunk_of(sess, chunk_id) or {}
        p = self.store.progress.setdefault(sess["studentId"], {"chunks": {}})
        key = chunk_key(sess["chapterId"], chunk_id)
        prev = p["chunks"].get(key, {})
        if not (prev.get("status") == "learned" and status == "skipped"):   # never downgrade a learned part
            p["chunks"][key] = {"status": status, "at": iso(now()), "session": sess["id"]}
        self.store.queue_write(f"progress/{sess['studentId']}.json", p)
        sess["chunkDone"] = {"id": chunk_id, "title": ch.get("title", ""), "status": status, "quizId": ch.get("quizId"),
                             "ideas": [{"atom": a, "got": a in sess.get("chunkRight", {}).get(chunk_id, []),
                                        "misses": sum(1 for x in sess["attempts"] if a in x.get("atom_ids", []) and not x.get("correct"))}
                                       for a in ch.get("atom_ids", [])]}

    def progress_view(self, sess: dict) -> dict | None:
        """What the chat header shows for a Learn session in parts."""
        t = topic_of(sess["chapterId"], sess.get("topicId"))
        if not t or not t.get("chunks") or sess.get("kind") != "learn":
            return None
        prog = self.store.progress.get(sess["studentId"], {})
        cur = current_step(sess)
        cur_chunk = cur["chunk"] if cur and cur.get("chunk") else None
        names = {a["id"]: a["statement"] for a in CHAPTERS[sess["chapterId"]]["atoms"]}
        parts, learnt = [], 0
        for c in t["chunks"]:
            stt = chunk_status(prog, sess["chapterId"], c["id"])
            if stt == "learned":
                learnt += len(c["atom_ids"])
            elif c["id"] == cur_chunk:
                learnt += len(sess.get("chunkRight", {}).get(c["id"], []))
            parts.append({"id": c["id"], "title": c["title"], "question": c.get("question", ""), "quizId": c.get("quizId"),
                          "status": "now" if c["id"] == cur_chunk else stt, "ideas": len(c["atom_ids"])})
        ideas = []
        if cur_chunk:
            right = set(sess.get("chunkRight", {}).get(cur_chunk, []))
            following = set(sess.get("chunkFollowing", {}).get(cur_chunk, []))
            tried = set(sess.get("chunkTried", {}).get(cur_chunk, []))
            ideas = [{"atom": a, "idea": names.get(a, ""), "status": "got it" if a in right else "following" if a in following
                      else "learning" if a in tried else "not yet"}
                     for a in (chunk_of(sess, cur_chunk) or {}).get("atom_ids", [])]
        return {"parts": parts, "current": cur_chunk, "learnt": learnt, "of": len(t["atom_ids"]), "ideas": ideas,
                "chunkDone": sess.get("chunkDone")}

    def summary(self, sess: dict) -> dict:
        moved: dict[str, list] = {}
        for att in sess["attempts"]:
            for c in att["changes"]:
                moved.setdefault(c["atom"], [c["from"], c["to"]])[1] = c["to"]
        names = {a["id"]: a["statement"] for a in CHAPTERS[sess["chapterId"]]["atoms"]}
        up = [{"atom": a, "idea": names.get(a, ""), "to": v[1]} for a, v in moved.items() if v[1] > v[0]]
        down = [{"atom": a, "idea": names.get(a, ""), "to": v[1]} for a, v in moved.items() if v[1] < v[0]]
        right = sum(1 for x in sess["attempts"] if x.get("correct"))
        nxt = None
        if sess.get("topicId"):
            t = topic_of(sess["chapterId"], sess["topicId"])
            if t and t.get("chunks") and sess.get("kind") == "learn":
                prog = self.store.progress.get(sess["studentId"], {})
                left = [c for c in t["chunks"] if chunk_status(prog, sess["chapterId"], c["id"]) != "learned"]
                if left:   # never send a student to a quiz on ideas they haven't been taught
                    nxt = {"kind": "learn", "topicId": t["id"], "chunkId": left[0]["id"],
                           "label": f"Continue learning: {left[0]['title']}"}
                elif t.get("quizId"):
                    nxt = {"kind": "quiz", "id": t["quizId"], "label": f"Take the {t['title']} topic quiz"}
            elif t and t.get("quizId"):
                nxt = {"kind": "quiz", "id": t["quizId"], "label": f"Take the {t['title']} quiz"}
        return {"steps": sum(1 for st in sess["plan"] if st["status"] == "done"), "of": len(sess["plan"]),
                "answered": len(sess["attempts"]), "right": right, "up": up, "down": down, "next": nxt}

    def _public(self, sess: dict) -> dict:
        cur = current_step(sess)
        plan = sess["plan"]
        if cur is not None and cur.get("chunk"):     # show only the current part's steps
            plan = [st for st in plan if st.get("chunk") == cur["chunk"]]
        return {"sessionId": sess["id"], "kind": sess["kind"], "goal": sess["goal"], "complete": bool(sess.get("complete")),
                "plan": [{"label": st["label"], "status": st["status"]} for st in plan],
                "step": plan.index(cur) if cur in plan else len(plan), "summary": sess.get("summary"),
                "parts": self.progress_view(sess)}

    def _run(self, sess: dict) -> str:
        cur = current_step(sess)
        if cur is not None:
            cur["exchanges"] += 1
            if cur.get("chunk"):
                sess.setdefault("chunkStarted", {}).setdefault(cur["chunk"], iso(now()))
            note = step_note(sess, cur)
            if sess.pop("greet", None) and not any(m["role"] == "tutor" for m in sess["transcript"]):
                note = f"The student is {self.students[sess['studentId']]['name']}. Greet them by name in a few words, then begin.\n" + note
            sess["messages"].append({"role": "system", "content": note})
        else:
            sess["messages"].append({"role": "system", "content": "The session is complete. Answer any last question briefly and kindly; do not start new questions. Point them to the next thing on their summary card, or ending the session."})
        effort = sess.setdefault("effort", SESSION_EFFORT)
        mode = self.store.settings.get("tutorRouting", "opus")
        model = FABLE if mode == "fable" else OPUS
        return self._turn(sess, model, effort, f"step: {cur['label'] if cur else 'after end'}")

    def start(self, student_id: str, chapter_id: str, kind: str, topic_id: str | None = None,
              attempt_id: str | None = None, fix_items: list | None = None, chunk_id: str | None = None) -> dict:
        if spent_today(self.store, student_id) >= DAILY_CAP_USD:
            raise CapReached()
        name = self.students[student_id]["name"]
        topic = topic_of(chapter_id, topic_id) if topic_id else None
        if kind in ("learn", "ask") and not topic:
            raise ValueError("unknown topic")
        m = self.store.mastery.get(student_id, {})
        goal, steps = build_plan(kind, chapter_id, m, topic, fix_items, self.store.progress.get(student_id, {}), chunk_id)
        if kind == "review" and len(steps) <= 1:
            raise ValueError("nothing to review yet")
        sid = now().strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
        sess = {"id": sid, "studentId": student_id, "setId": chapter_id, "chapterId": chapter_id, "topicId": topic_id,
                "attemptId": attempt_id, "kind": kind, "mode": kind, "goal": goal, "plan": steps,
                "started": iso(now()), "updated": iso(now()), "messages": [], "transcript": [], "attempts": [],
                "flags": [], "tools": [], "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0},
                "confidence": None, "studentMessages": 0, "effort": SESSION_EFFORT,
                "scope": session_scope(CHAPTERS[chapter_id], topic, steps),
                "prior": self._prior_on_topic(student_id, chapter_id, topic_id) if kind == "learn" else None}
        opener = {"learn": f"I'd like to learn: {topic['title'] if topic else ''}.", "ask": f"I have a question about {topic['title'] if topic else 'this topic'}.",
                  "fix": "Help me fix my quiz mistakes.", "review": "Let's do my review."}[kind]
        sess["messages"] = [{"role": "user", "content": opener}]
        sess["greet"] = f"The student is {name}. Greet them by name in a few words, then begin the first step."
        sess["transcript"].append({"role": "student", "text": opener, "t": iso(now())})
        with self._lock(sid):
            self.store.chats[sid] = sess
            reply = self._run(sess)
            sess["updated"] = iso(now())
            self.store.queue_write(f"chats/{sid}.json", sess)
        return {**self._public(sess), "reply": reply, "meta": _meta(sess)}

    def _prior_on_topic(self, student_id: str, chapter_id: str, topic_id: str | None) -> dict | None:
        """What the student already did on this topic in earlier Learn sessions, so a new one doesn't start over."""
        if not topic_id:
            return None
        earlier = [s for s in self.store.chats.values()
                   if s["studentId"] == student_id and s.get("chapterId") == chapter_id and s.get("topicId") == topic_id
                   and s.get("kind") == "learn" and sum(1 for m in s["transcript"] if m["role"] == "student") >= 2]
        if not earlier:
            return None
        t = topic_of(chapter_id, topic_id) or {}
        prog = self.store.progress.get(student_id, {})
        learnt = [c["title"] for c in t.get("chunks", []) if chunk_status(prog, chapter_id, c["id"]) == "learned"]
        return {"sessions": len(earlier), "last": max(s["updated"] for s in earlier)[:10], "learnt": learnt}

    def sessions_for(self, student_id: str, chapter_id: str | None = None) -> list[dict]:
        """The student's own past chats (newest first) for the 'Your tutor chats' list."""
        out = []
        for s in self.store.chats.values():
            if s["studentId"] != student_id or (chapter_id and s.get("chapterId") != chapter_id):
                continue
            n_student = sum(1 for m in s["transcript"] if m["role"] == "student")
            if n_student < 2:        # opened and left straight away: nothing to go back to
                continue
            t = topic_of(s["chapterId"], s.get("topicId")) if s.get("topicId") else None
            cur = current_step(s)
            ch = chunk_of(s, cur["chunk"]) if cur and cur.get("chunk") else None
            prog = self.store.progress.get(student_id, {})
            out.append({"id": s["id"], "chapterId": s["chapterId"], "topicId": s.get("topicId"), "kind": s["kind"],
                        "title": (t or {}).get("title") or s.get("goal", ""), "started": s["started"], "updated": s["updated"],
                        "messages": len(s["transcript"]), "complete": bool(s.get("complete")),
                        "atPart": ch.get("title") if ch else None, "atChunk": ch.get("id") if ch else None,
                        "atPartLearnt": bool(ch) and chunk_status(prog, s["chapterId"], ch["id"]) == "learned"})
        return sorted(out, key=lambda x: x["updated"], reverse=True)

    def open_session(self, sid: str, student_id: str) -> dict:
        sess = self.store.chats.get(sid)
        if not sess or sess["studentId"] != student_id:
            raise KeyError(sid)
        msgs = [{"who": "tutor" if m["role"] == "tutor" else "me", "text": m["text"], "conf": m.get("confidence")}
                for m in sess["transcript"]]
        return {**self._public(sess), "chapterId": sess["chapterId"], "topicId": sess.get("topicId"), "msgs": msgs}

    def message(self, sid: str, text: str, confidence: str | None, focus: dict | None = None) -> dict:
        sess = self.store.chats[sid]
        if spent_today(self.store, sess["studentId"]) >= DAILY_CAP_USD:
            raise CapReached()
        with self._lock(sid):
            n_before = len(sess["attempts"])
            sess.pop("chunkDone", None)          # the student has moved on from the end-of-part card
            sess["confidence"] = confidence
            sess["studentMessages"] = sess.get("studentMessages", 0) + 1
            tagged = text + (f"\n[confidence: {confidence}]" if confidence else "")
            sess["messages"].append({"role": "user", "content": tagged})
            sess["transcript"].append({"role": "student", "text": text, "confidence": confidence, "t": iso(now()),
                                       **({"focus": focus} if focus else {})})
            reply = self._run(sess)
            sess["updated"] = iso(now())
            self.store.queue_write(f"chats/{sid}.json", sess)
            changes = [c for att in sess["attempts"][n_before:] for c in att["changes"]]
        return {**self._public(sess), "reply": reply, "changes": changes, "meta": _meta(sess)}