alix 0.1.0

Your personal AI tutor — built for understanding, not just remembering.
Documentation
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
//! The interactive review TUI built on ratatui.

use std::{
    collections::{BTreeSet, HashMap, HashSet},
    path::PathBuf,
    sync::mpsc::{Receiver, TryRecvError},
    time::Duration,
};

use anyhow::Result;
use ratatui::{
    Frame,
    crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    layout::{Constraint, Layout, Position, Rect},
    style::{Color, Modifier, Style, Stylize},
    text::{Line, Span},
    widgets::{Paragraph, Wrap},
};

use crate::{
    answer::{FuzzyResult, Mode, TypingValidator, best_prefix_match, grade_fuzzy},
    ask,
    card::Card,
    choice::{self, ChoiceQuestion},
    config::{AskConfig, Bindings, ExamConfig, Key, KeyPattern, Strictness},
    deck::{self, Deck, DeckState},
    exam,
    render::{self, ContextSpan, NoteUnit},
    scheduler::Grade,
    session::{Session, SessionStats},
    store::Store,
    time,
};

pub(crate) const HEADER_STYLE: Style = Style::new().fg(Color::Black).bg(Color::Cyan);

/// What the user is currently doing.
enum Phase {
    /// Typing the answer character by character. Multi-line answers are graded
    /// order-independently: a row is matched to whichever expected line it
    /// completes, so the items can be typed in any order.
    Typing {
        /// The expected back lines.
        expected: Vec<String>,
        /// Which expected lines a completed row has already claimed (parallel
        /// to `expected`).
        claimed: Vec<bool>,
        /// Completed rows, in entry order — for grading and the feedback view.
        done: Vec<FuzzyResult>,
        /// The row being typed; its target is re-chosen as the user types.
        current: TypingValidator,
        /// Currently displayed hint text, cleared on the next keystroke.
        hint: Option<String>,
    },
    /// Typing whole lines, submitted with Enter and graded fuzzily.
    Fuzzy {
        results: Vec<FuzzyResult>,
        input: String,
    },
    /// Looking at the front, answer hidden until revealed.
    Flip { revealed: bool },
    /// Understanding card: type an explanation (optional, free text — not
    /// checked), reveal the back lines (the key points), then self-grade on
    /// whether you covered them. `input` is the typed reconstruction.
    Explain { input: String, revealed: bool },
    /// Revealing the back one line at a time. `revealed` is the number of
    /// back lines shown so far; once it reaches the line count the card is
    /// fully uncovered and graded like flip mode.
    LineByLine { revealed: usize },
    /// Picking one of several offered answers. `selected` is set once the
    /// user chose (the grade is applied at that moment); the card is a
    /// snapshot because the session advances on grading.
    Choice {
        card: Card,
        question: ChoiceQuestion,
        selected: Option<usize>,
    },
    /// Showing the result of the answered card (typing or fuzzy mode). `mode`
    /// is the mode the card was answered in, so the view can label and render
    /// the lines correctly; `results` holds one graded line per back line.
    Feedback {
        card: Card,
        grade: Grade,
        mode: Mode,
        results: Vec<FuzzyResult>,
    },
    /// Asking Claude about a card; entered from a post-answer screen and
    /// returned from with Esc. `return_to` restores that screen.
    Ask {
        return_to: Box<Phase>,
        card: Card,
        /// Completed question/answer exchanges.
        transcript: Vec<ask::Exchange>,
        /// The question currently being typed.
        input: String,
        /// Caret position within `input`, counted in characters (0..=len).
        cursor: usize,
        /// A pending CLI call, if any.
        waiting: Option<Waiting>,
        /// Scroll offset of the transcript (clamped while drawing).
        scroll: u16,
        /// Transient status line (errors, "note saved").
        status: Option<String>,
    },
    /// The session is over; showing totals.
    Summary,
}

/// A pending background CLI call.
struct Waiting {
    rx: Receiver<ask::Reply>,
    purpose: Purpose,
}

/// What a pending CLI call is for.
enum Purpose {
    /// A question; holds the text to add to the transcript on success.
    Question(String),
    /// Condensing the conversation into note lines for the deck file.
    Condense,
}

/// Per-deck information the TUI needs, keyed by subject.
pub struct DeckInfo {
    /// The deck file, for saving notes from the ask view.
    pub path: PathBuf,
    /// Reference links (`% link:` lines) offered to Claude as background.
    pub links: Vec<String>,
    /// The deck's `% source:` project root, for the grounded ask-tutor
    /// (`[ask] source_access`); `None` when there's no local source.
    pub source_root: Option<PathBuf>,
    /// Whether the grounded tutor may read this deck's source — the *effective*
    /// value (the deck's workspace `source_access` override, else the global
    /// `[ask] source_access`).
    pub source_access: bool,
    /// The deck's source base, for resolving a card's `% at:` citation excerpt
    /// on reveal (fact-card citations).
    pub source_base: crate::trace::SourceBase,
}

/// Static settings of a review run.
pub struct Options {
    /// CLI `--mode` override, applied to every card. `None` lets each card use
    /// its own mode (card `% mode:` > deck `% mode:` > built-in default).
    pub mode_override: Option<Mode>,
    /// Fuzzy-mode typo tolerance per line.
    pub max_typos: usize,
    /// Deck names shown in the header.
    pub deck_label: String,
    /// Key bindings.
    pub keys: Bindings,
    /// Ask-Claude settings.
    pub ask: AskConfig,
    /// Loaded decks by subject.
    pub decks: HashMap<String, DeckInfo>,
}

/// The review application.
pub struct App {
    session: Session,
    store: Store,
    options: Options,
    phase: Phase,
    /// Counters across all sessions of this run (restarts included).
    totals: SessionStats,
    /// Set when a restart found nothing due; shown on the summary screen.
    nothing_due: bool,
    /// Largest useful transcript scroll offset, cached while drawing.
    ask_max_scroll: std::cell::Cell<u16>,
    /// The CLI conversation spanning this run; created lazily, reset on
    /// errors.
    ask_session: ask::CliSession,
    /// Cards marked for removal: deck subject → front line numbers, applied to
    /// the deck files when the run ends.
    removed_lines: HashMap<String, BTreeSet<usize>>,
    /// Identity hashes of removed cards, pruned from the store at the end.
    removed_ids: HashSet<u64>,
    /// Set at the summary when the user picks a follow-up for a deck that became
    /// `exam due` this session — sit its exam, or browse it; `run` returns it so
    /// `main` launches that after the review app exits.
    next_action: Option<AfterReview>,
    quit: bool,
    /// Set when the user asked to quit mid-session: a confirmation prompt is
    /// shown, and the quit only goes through once they confirm it.
    confirming_quit: bool,
    /// Showing a cited card's source excerpt in place of its answer (`% at:`),
    /// toggled with `s`; reset for each new card.
    citation_view: bool,
}

/// What the user chose at the session-end summary, for `main` to act on after
/// the review app exits.
pub enum AfterReview {
    /// Sit the deck's AI exam.
    Exam(PathBuf),
    /// Browse the deck — a read-only walk through its cards.
    Browse(PathBuf),
}

impl App {
    /// Creates the app and primes the first card.
    pub fn new(session: Session, store: Store, options: Options) -> Self {
        let mut app = Self {
            session,
            store,
            options,
            phase: Phase::Summary,
            totals: SessionStats::default(),
            nothing_due: false,
            ask_max_scroll: std::cell::Cell::new(0),
            ask_session: ask::CliSession::new(),
            removed_lines: HashMap::new(),
            removed_ids: HashSet::new(),
            next_action: None,
            quit: false,
            confirming_quit: false,
            citation_view: false,
        };
        app.start_card();
        app
    }

    /// Runs the TUI until the user quits. Returns the counters accumulated over
    /// all sessions of this run, plus the deck whose exam the user asked to sit
    /// at the summary (if any).
    pub fn run(mut self) -> Result<(SessionStats, Option<AfterReview>)> {
        let mut terminal = ratatui::init();
        let result = self.event_loop(&mut terminal);
        ratatui::restore();
        // Apply pending card removals to the deck files now that the terminal
        // is back, so any message is visible. This also prunes their progress.
        self.flush_removals();
        // Progress is saved after every grade, but save once more in case
        // the loop exited between grades (and to persist the prunes above).
        self.store.save()?;
        result?;
        Ok((self.totals, self.next_action.take()))
    }

    /// Like [`run`](Self::run) but on a `terminal` the caller already set up (and
    /// will restore), so the picker can launch a review and resume afterwards
    /// without tearing the TUI down and back up.
    pub fn run_on(
        mut self,
        terminal: &mut ratatui::DefaultTerminal,
    ) -> Result<(SessionStats, Option<AfterReview>)> {
        let result = self.event_loop(terminal);
        self.flush_removals();
        self.store.save()?;
        result?;
        Ok((self.totals, self.next_action.take()))
    }

    /// Starts a new session over the same decks, or flags that nothing is
    /// due yet so the summary can say so.
    fn try_restart(&mut self) {
        if self.session.restart(&self.store, time::now_ms()) {
            self.nothing_due = false;
            self.start_card();
        } else {
            self.nothing_due = true;
        }
    }

    /// Decks in this session that are now `exam due` (drilled, `% source:`, not
    /// yet mastered) — offered at the summary. Sorted by subject.
    fn exam_due_decks(&self) -> Vec<(String, PathBuf)> {
        let mut out: Vec<(String, PathBuf)> = self
            .options
            .decks
            .iter()
            .filter_map(|(subject, info)| {
                let deck = Deck::load(&info.path).ok()?;
                (!deck.sources.is_empty() && deck.state(&self.store) == DeckState::ExamDue)
                    .then(|| (subject.clone(), info.path.clone()))
            })
            .collect();
        out.sort();
        out
    }

    fn event_loop(&mut self, terminal: &mut ratatui::DefaultTerminal) -> Result<()> {
        while !self.quit {
            terminal.draw(|frame| self.draw(frame))?;
            // Poll instead of blocking so pending CLI replies (and the
            // spinner) are picked up while no key is pressed.
            if event::poll(Duration::from_millis(100))? {
                match event::read()? {
                    // Resize with the event's dimensions so the redraw reflows
                    // immediately instead of waiting for the next keypress.
                    Event::Resize(w, h) => terminal.resize(Rect::new(0, 0, w, h))?,
                    Event::Key(key) if key.kind == KeyEventKind::Press => self.handle_key(key)?,
                    _ => {}
                }
            }
            self.poll_ask();
        }
        Ok(())
    }

    /// Checks whether a pending ask-Claude call has delivered its reply.
    fn poll_ask(&mut self) {
        let Phase::Ask {
            card,
            transcript,
            waiting,
            scroll,
            status,
            ..
        } = &mut self.phase
        else {
            return;
        };
        let Some(w) = waiting else {
            return;
        };
        let reply = match w.rx.try_recv() {
            Ok(reply) => reply,
            Err(TryRecvError::Empty) => return,
            Err(TryRecvError::Disconnected) => {
                ask::Reply::Error("the ask thread died unexpectedly".to_string())
            }
        };
        match (reply, &w.purpose) {
            (ask::Reply::Answer(answer), Purpose::Question(question)) => {
                // The CLI call succeeded, so the session now exists and
                // later calls resume it.
                self.ask_session.started = true;
                transcript.push((question.clone(), answer));
                // Jump to the bottom of the transcript (clamped on draw).
                *scroll = self.ask_max_scroll.get().saturating_add(100);
            }
            (ask::Reply::Answer(text), Purpose::Condense) => {
                self.ask_session.started = true;
                let notes = ask::extract_note_lines(&text);
                *status = Some(match self.options.decks.get(&*card.subject) {
                    None => format!("no deck file known for {}", card.subject),
                    Some(info) => match deck::append_note(&info.path, card.line, &notes) {
                        Ok(()) if notes.is_empty() => "nothing to save".to_string(),
                        Ok(()) => {
                            // Show the note immediately, without re-reading the
                            // deck: on the ask view's card recap (this clone) and
                            // on the session card the review redraws on return.
                            card.append_note(&notes);
                            if let Some(sc) = self.session.current_mut()
                                && sc.id() == card.id()
                            {
                                sc.append_note(&notes);
                            }
                            format!("note saved to {}", info.path.display())
                        }
                        Err(e) => format!("cannot save note: {e}"),
                    },
                });
            }
            (ask::Reply::Error(e), _) => {
                *status = Some(e);
                // Don't try to resume a session in an unknown state; the
                // next question starts a fresh one.
                self.ask_session = ask::CliSession::new();
            }
        }
        *waiting = None;
    }

    /// Sets up the phase for the next card, or the summary if none is left.
    fn start_card(&mut self) {
        self.citation_view = false; // a new card starts on its answer, not its source
        let Some(card) = self.session.current() else {
            // Reaching the summary: flag up front whether a new session could
            // start, so the screen can say "nothing due" without the user
            // having to press the restart key first.
            self.nothing_due = !self.session.has_due_now(&self.store, time::now_ms());
            self.phase = Phase::Summary;
            return;
        };
        // CLI override wins; otherwise the card's own mode (card > deck), else
        // the built-in default.
        let mode = self.options.mode_override.or(card.mode).unwrap_or_default();
        self.phase = match mode {
            Mode::Typing => {
                let expected = card.back.clone();
                let first = expected.first().cloned().unwrap_or_default();
                Phase::Typing {
                    claimed: vec![false; expected.len()],
                    current: TypingValidator::new(&first),
                    done: Vec::new(),
                    expected,
                    hint: None,
                }
            }
            Mode::Fuzzy => Phase::Fuzzy {
                results: Vec::new(),
                input: String::new(),
            },
            Mode::Flip => Phase::Flip { revealed: false },
            Mode::Explain => Phase::Explain {
                input: String::new(),
                revealed: false,
            },
            Mode::LineByLine => Phase::LineByLine { revealed: 0 },
            Mode::Choice => {
                match choice::build(card, self.session.cards(), time::now_ms()) {
                    Some(question) => Phase::Choice {
                        card: card.clone(),
                        question,
                        selected: None,
                    },
                    // Not enough distinct answers in the session to build
                    // distractors; fall back to flip mode for this card.
                    None => Phase::Flip { revealed: false },
                }
            }
        };
    }

    /// Applies a grade for the current card and persists the progress.
    fn apply_grade(&mut self, grade: Grade) -> Result<()> {
        self.session.grade(&mut self.store, grade, time::now_ms());
        self.totals.reviews += 1;
        if grade.passed() {
            self.totals.passed += 1;
        } else {
            self.totals.failed += 1;
        }
        Ok(self.store.save()?)
    }

    /// Grades the current card and moves to the feedback view (typing and
    /// fuzzy mode).
    fn finish_card(&mut self, grade: Grade, mode: Mode, results: Vec<FuzzyResult>) -> Result<()> {
        let card = self.session.current().expect("a card is active").clone();
        self.apply_grade(grade)?;
        self.phase = Phase::Feedback {
            card,
            grade,
            mode,
            results,
        };
        Ok(())
    }

    /// The card currently on screen: the snapshot held by the phase after
    /// grading (Feedback / an answered Choice), else the session's current card.
    fn current_card(&self) -> Option<&Card> {
        match &self.phase {
            Phase::Feedback { card, .. } | Phase::Choice { card, .. } => Some(card),
            _ => self.session.current(),
        }
    }

    /// Whether the on-screen `card` is answered/revealed — the states in which
    /// its `% at:` source citation can be shown (and `s` toggles to it).
    fn answered(&self, card: &Card) -> bool {
        match &self.phase {
            Phase::Flip { revealed } | Phase::Explain { revealed, .. } => *revealed,
            Phase::LineByLine { revealed } => *revealed >= card.back.len(),
            Phase::Feedback { .. } => true,
            Phase::Choice { selected, .. } => selected.is_some(),
            _ => false,
        }
    }

    /// Renders `card`'s cited source excerpt (line-numbered), resolved live
    /// against its deck's source base — or a dim reason it can't be read.
    fn push_source(&self, lines: &mut Vec<Line>, card: &Card) {
        let resolved = self
            .options
            .decks
            .get(&*card.subject)
            .zip(card.at.as_deref())
            .map(|(info, at)| info.source_base.excerpt(at));
        match resolved {
            Some(Ok(ex)) => {
                for (n, text) in &ex.lines {
                    lines.push(Line::from(vec![
                        Span::styled(format!("{n:>4} "), Style::new().fg(Color::DarkGray)),
                        Span::raw(text.clone()),
                    ]));
                }
                if ex.truncated {
                    lines.push(Line::from("    … (truncated)".dim()));
                }
            }
            Some(Err(e)) => lines.push(Line::from(format!("source unavailable: {e:#}").dim())),
            None => lines.push(Line::from("source unavailable".dim())),
        }
    }

    /// The shared tail under an answered card: its note, then the grade prompt
    /// (Flip/Explain/LineByLine) or the PASSED/FAILED badge (Feedback/Choice).
    fn push_answer_tail(&self, lines: &mut Vec<Line>, card: &Card, width: u16) {
        push_note(lines, card, width);
        lines.push(Line::default());
        match &self.phase {
            Phase::Flip { .. } | Phase::LineByLine { .. } => {
                lines.push(Line::from("How well did you know it?".italic()));
            }
            Phase::Explain { .. } => {
                lines.push(Line::from("How well did you cover them?".italic()));
            }
            Phase::Feedback { grade, .. } => lines.push(passed_failed_badge(grade.passed())),
            Phase::Choice {
                question,
                selected: Some(s),
                ..
            } => lines.push(passed_failed_badge(*s == question.correct)),
            _ => {}
        }
    }

    /// The dim affordance line telling the user `s` swaps answer ⟷ source.
    fn push_citation_hint(&self, lines: &mut Vec<Line>) {
        lines.push(Line::default());
        let hint = if self.citation_view {
            "¶  s  show the answer"
        } else {
            "</>  s  view the source"
        };
        lines.push(Line::from(hint.dim()));
    }

    /// Grades the current card and goes straight to the next one (flip mode:
    /// the answer was already revealed, a feedback screen would only cost an
    /// extra keypress).
    fn finish_card_and_advance(&mut self, grade: Grade) -> Result<()> {
        self.apply_grade(grade)?;
        self.start_card();
        Ok(())
    }

    /// Marks the current card (and any cloze siblings) for removal from its
    /// deck file, drops it from the queue, and moves on. The file edits and
    /// progress pruning happen together when the run ends, in
    /// [`flush_removals`].
    fn remove_card(&mut self) {
        let removed = self.session.remove_current();
        let Some(first) = removed.first() else {
            return;
        };
        // All removed cards share one source block (same subject and line).
        self.removed_lines
            .entry(first.subject.to_string())
            .or_default()
            .insert(first.line);
        for card in &removed {
            self.removed_ids.insert(card.id());
        }
        self.start_card();
    }

    /// Deletes every card marked for removal from its deck file and prunes the
    /// matching progress entries. Best-effort: a file that cannot be rewritten
    /// is reported but does not abort the others. Called once, after the
    /// terminal is restored.
    fn flush_removals(&mut self) {
        if self.removed_lines.is_empty() {
            return;
        }
        let mut cards = 0;
        let mut files = 0;
        for (subject, lines) in &self.removed_lines {
            let Some(info) = self.options.decks.get(subject) else {
                eprintln!("warning: no deck file known for {subject}; cannot remove cards");
                continue;
            };
            let lines: Vec<usize> = lines.iter().copied().collect();
            cards += lines.len();
            match deck::remove_cards(&info.path, &lines) {
                Ok(()) => files += 1,
                Err(e) => eprintln!("warning: could not update {}: {e}", info.path.display()),
            }
        }
        for id in &self.removed_ids {
            self.store.remove(*id);
        }
        if files > 0 {
            eprintln!("Removed {cards} card(s) from {files} deck file(s).");
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> Result<()> {
        // The ask view has its own key handling (free-text input, and Esc
        // means "back", not "quit").
        if matches!(self.phase, Phase::Ask { .. }) {
            self.handle_ask_key(key);
            return Ok(());
        }

        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // A pending quit confirmation captures the next key: Enter / `y` leaves,
        // anything else stays in the session.
        if self.confirming_quit {
            self.confirming_quit = false;
            if matches!(key.code, KeyCode::Enter | KeyCode::Char('y')) {
                self.quit = true;
            }
            return Ok(());
        }

        let pattern = key_pattern(&key);

        // While typing an answer, plain character bindings must not shadow
        // text input, so only ctrl-/special-key bindings are honored there.
        // Explain mode takes free text only until the points are revealed.
        let text_input = matches!(
            self.phase,
            Phase::Typing { .. }
                | Phase::Fuzzy { .. }
                | Phase::Explain {
                    revealed: false,
                    ..
                }
        );
        let hit = |list: &[KeyPattern]| {
            pattern.is_some_and(|p| {
                list.iter()
                    .any(|b| *b == p && !(text_input && b.is_plain_char()))
            })
        };

        // Bindings that apply across phases.
        let quit_hit = hit(&self.options.keys.quit);
        let skip_hit = hit(&self.options.keys.skip);
        let remove_hit = hit(&self.options.keys.remove);
        let restart_hit = hit(&self.options.keys.restart);
        let ask_hit = hit(&self.options.keys.ask);
        let hint_hit = hit(&self.options.keys.hint);
        let submit_hit = hit(&self.options.keys.submit);
        let reveal_hit = hit(&self.options.keys.reveal);
        let again_hit = hit(&self.options.keys.again);
        let good_hit = hit(&self.options.keys.good);
        let easy_hit = hit(&self.options.keys.easy);
        let cont_hit = hit(&self.options.keys.cont);

        if quit_hit {
            // Quitting mid-session abandons the queued cards, so confirm first.
            // A finished session (summary) or a hard Ctrl-C leaves immediately.
            if ctrl || self.session.is_finished() {
                self.quit = true;
            } else {
                self.confirming_quit = true;
            }
            return Ok(());
        }
        // Skipping only makes sense while a card is still unanswered.
        let answerable = !matches!(
            self.phase,
            Phase::Summary
                | Phase::Feedback { .. }
                | Phase::Choice {
                    selected: Some(_),
                    ..
                }
        );
        if skip_hit && answerable {
            self.session.skip();
            self.start_card();
            return Ok(());
        }
        // Marking for removal makes sense on the card you'd otherwise answer.
        if remove_hit && answerable {
            self.remove_card();
            return Ok(());
        }
        // `s` swaps a cited card between its answer and its source excerpt, once
        // answered (so it never shadows plain-`s` while typing an answer).
        if !ctrl && matches!(key.code, KeyCode::Char('s') | KeyCode::Char('S')) {
            let cited = match self.current_card() {
                Some(c) => c.at.is_some() && self.answered(c),
                None => false,
            };
            if cited {
                self.citation_view = !self.citation_view;
                return Ok(());
            }
        }

        match &mut self.phase {
            Phase::Typing {
                expected,
                claimed,
                done,
                current,
                hint,
            } => {
                if hint_hit {
                    // Default bindings: Tab, Ctrl-H, and Ctrl-Backspace
                    // (legacy terminals deliver Ctrl-H as the latter).
                    *hint = Some(current.hint());
                    return Ok(());
                }
                match key.code {
                    KeyCode::Backspace if !ctrl => {
                        *hint = None;
                        current.backspace();
                        retarget(current, expected, claimed);
                    }
                    KeyCode::Char(c) if !ctrl => {
                        *hint = None;
                        current.type_char(c);
                        retarget(current, expected, claimed);
                        if current.is_complete() {
                            // Claim the (still-unclaimed) expected line this row
                            // matched.
                            let target = current.expected();
                            if let Some(idx) =
                                (0..expected.len()).find(|&i| !claimed[i] && expected[i] == target)
                            {
                                claimed[idx] = true;
                            }
                            done.push(typing_result(current));
                            if claimed.iter().all(|&c| c) {
                                let results = std::mem::take(done);
                                let passed = results.iter().all(|r| r.passed);
                                let grade = if passed { Grade::Pass } else { Grade::Fail };
                                self.finish_card(grade, Mode::Typing, results)?;
                            } else {
                                // Begin the next row on a still-unclaimed line.
                                let next = expected
                                    .iter()
                                    .enumerate()
                                    .find(|(i, _)| !claimed[*i])
                                    .map(|(_, e)| e.clone())
                                    .unwrap_or_default();
                                *current = TypingValidator::new(&next);
                            }
                        }
                    }
                    _ => {}
                }
            }
            Phase::Fuzzy { results, input } => {
                if submit_hit {
                    let card = self.session.current().expect("a card is active");
                    let expected = &card.back[results.len()];
                    results.push(grade_fuzzy(input, expected, self.options.max_typos));
                    input.clear();
                    if results.len() == card.back.len() {
                        let passed = results.iter().all(|r| r.passed);
                        let grade = if passed { Grade::Pass } else { Grade::Fail };
                        let results = std::mem::take(results);
                        self.finish_card(grade, Mode::Fuzzy, results)?;
                    }
                    return Ok(());
                }
                match key.code {
                    KeyCode::Backspace if !ctrl => {
                        input.pop();
                    }
                    KeyCode::Char(c) if !ctrl => input.push(c),
                    _ => {}
                }
            }
            Phase::Flip { revealed } => {
                if !*revealed {
                    if reveal_hit {
                        *revealed = true;
                    }
                } else if again_hit {
                    self.finish_card_and_advance(Grade::Fail)?;
                } else if good_hit {
                    self.finish_card_and_advance(Grade::Pass)?;
                } else if easy_hit {
                    self.finish_card_and_advance(Grade::Easy)?;
                } else if ask_hit {
                    self.enter_ask();
                }
            }
            Phase::Explain { input, revealed } => {
                if !*revealed {
                    // Free-text reconstruction; Enter reveals the points (a
                    // plain-char reveal binding would be swallowed by the input).
                    match key.code {
                        KeyCode::Enter => *revealed = true,
                        KeyCode::Backspace if !ctrl => {
                            input.pop();
                        }
                        KeyCode::Char(c) if !ctrl => input.push(c),
                        _ => {}
                    }
                } else if again_hit {
                    self.finish_card_and_advance(Grade::Fail)?;
                } else if good_hit {
                    self.finish_card_and_advance(Grade::Pass)?;
                } else if easy_hit {
                    self.finish_card_and_advance(Grade::Easy)?;
                } else if ask_hit {
                    self.enter_ask();
                }
            }
            Phase::LineByLine { revealed } => {
                let total = self.session.current().map_or(0, |c| c.back.len());
                if *revealed < total {
                    if reveal_hit {
                        *revealed += 1;
                    }
                } else if again_hit {
                    self.finish_card_and_advance(Grade::Fail)?;
                } else if good_hit {
                    self.finish_card_and_advance(Grade::Pass)?;
                } else if easy_hit {
                    self.finish_card_and_advance(Grade::Easy)?;
                } else if ask_hit {
                    self.enter_ask();
                }
            }
            Phase::Choice {
                question, selected, ..
            } => {
                if selected.is_none() {
                    if let KeyCode::Char(c @ '1'..='9') = key.code {
                        let index = c as usize - '1' as usize;
                        if index < question.options.len() {
                            *selected = Some(index);
                            let grade = if index == question.correct {
                                Grade::Pass
                            } else {
                                Grade::Fail
                            };
                            self.apply_grade(grade)?;
                        }
                    }
                } else if cont_hit {
                    self.start_card();
                } else if ask_hit {
                    self.enter_ask();
                }
            }
            Phase::Feedback { .. } => {
                if cont_hit {
                    self.start_card();
                } else if ask_hit {
                    self.enter_ask();
                }
            }
            // Handled by handle_ask_key before reaching this match.
            Phase::Ask { .. } => {}
            Phase::Summary => {
                // `x` sits the exam of a deck that became exam-due this session;
                // with nothing due the restart key is inert (the footer omits
                // it); any other key exits.
                let exam_due = self.exam_due_decks();
                if key.code == KeyCode::Char('x') && !exam_due.is_empty() {
                    self.next_action = Some(AfterReview::Exam(exam_due[0].1.clone()));
                    self.quit = true;
                } else if key.code == KeyCode::Char('b') && !exam_due.is_empty() {
                    self.next_action = Some(AfterReview::Browse(exam_due[0].1.clone()));
                    self.quit = true;
                } else if restart_hit && !self.nothing_due {
                    self.try_restart();
                } else {
                    self.quit = true;
                }
            }
        }
        Ok(())
    }

    /// Switches to the ask view for the card on screen, remembering the
    /// current screen to return to.
    fn enter_ask(&mut self) {
        let card = match &self.phase {
            Phase::Feedback { card, .. } | Phase::Choice { card, .. } => card.clone(),
            Phase::Flip { .. } | Phase::LineByLine { .. } | Phase::Explain { .. } => {
                match self.session.current() {
                    Some(card) => card.clone(),
                    None => return,
                }
            }
            _ => return,
        };
        let return_to = Box::new(std::mem::replace(&mut self.phase, Phase::Summary));
        self.phase = Phase::Ask {
            return_to,
            card,
            transcript: Vec::new(),
            input: String::new(),
            cursor: 0,
            waiting: None,
            scroll: 0,
            status: None,
        };
    }

    /// Key handling inside the ask view.
    fn handle_ask_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let pattern = key_pattern(&key);
        // Free-text input: only ctrl-/special-key bindings may act.
        let hit = |list: &[KeyPattern]| {
            pattern.is_some_and(|p| list.iter().any(|b| *b == p && !b.is_plain_char()))
        };
        let save_hit = hit(&self.options.keys.save_note);
        let max_scroll = self.ask_max_scroll.get();

        // Esc leaves the ask view (abandoning a pending call); Ctrl-C still
        // quits the whole app.
        if key.code == KeyCode::Esc {
            if let Phase::Ask { return_to, .. } = std::mem::replace(&mut self.phase, Phase::Summary)
            {
                self.phase = *return_to;
            }
            return;
        }
        if ctrl && key.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }

        let Phase::Ask {
            card,
            transcript,
            input,
            cursor,
            waiting,
            scroll,
            status,
            ..
        } = &mut self.phase
        else {
            return;
        };

        if save_hit {
            if !transcript.is_empty() && waiting.is_none() {
                // Ground the condense in the same source root as this card's
                // questions, so the CLI's working directory stays stable and the
                // conversation remains resumable.
                let root = self
                    .options
                    .decks
                    .get(&*card.subject)
                    .filter(|i| i.source_access)
                    .and_then(|i| i.source_root.as_deref());
                let ask_cfg = match root {
                    Some(r) => ask::with_source_root(&self.options.ask, r),
                    None => self.options.ask.clone(),
                };
                let prompt = ask::condense_prompt(card, transcript);
                let args = self.ask_session.args_in(ask_cfg.cwd.as_deref());
                *status = None;
                *waiting = Some(Waiting {
                    rx: ask::spawn(ask_cfg, prompt, args),
                    purpose: Purpose::Condense,
                });
            }
            return;
        }

        match key.code {
            KeyCode::Enter if waiting.is_none() && !input.trim().is_empty() => {
                let question = std::mem::take(input);
                *cursor = 0;
                let info = self.options.decks.get(&*card.subject);
                let links = info.map(|i| i.links.as_slice()).unwrap_or(&[]);
                // Ground the tutor in the card's source when source access is on
                // for this deck (its workspace override, else global) and it has
                // a local source root.
                let root = info
                    .filter(|i| i.source_access)
                    .and_then(|i| i.source_root.as_deref());
                let ask_cfg = match root {
                    Some(r) => ask::with_source_root(&self.options.ask, r),
                    None => self.options.ask.clone(),
                };
                // Reconcile the session with this call's cwd *before* the prompt:
                // a cwd change starts a fresh conversation, so `started` then
                // reports this as a first message (full card context).
                let args = self.ask_session.args_in(ask_cfg.cwd.as_deref());
                let prompt =
                    ask::question_prompt(card, links, &question, !self.ask_session.started, root);
                *status = None;
                *waiting = Some(Waiting {
                    rx: ask::spawn(ask_cfg, prompt, args),
                    purpose: Purpose::Question(question),
                });
            }
            KeyCode::Backspace if !ctrl => {
                // Delete the character to the left of the caret.
                if *cursor > 0 {
                    let byte = char_byte(input, *cursor - 1);
                    input.remove(byte);
                    *cursor -= 1;
                }
            }
            KeyCode::Delete if !ctrl => {
                // Delete the character under the caret.
                if let Some((byte, _)) = input.char_indices().nth(*cursor) {
                    input.remove(byte);
                }
            }
            KeyCode::Left => *cursor = cursor.saturating_sub(1),
            KeyCode::Right => *cursor = (*cursor + 1).min(input.chars().count()),
            KeyCode::Home => *cursor = 0,
            KeyCode::End => *cursor = input.chars().count(),
            KeyCode::Char('a') if ctrl => *cursor = 0,
            KeyCode::Char('e') if ctrl => *cursor = input.chars().count(),
            KeyCode::PageUp => *scroll = (*scroll).min(max_scroll).saturating_sub(5),
            KeyCode::PageDown => *scroll = (*scroll).saturating_add(5).min(max_scroll),
            KeyCode::Char('u') if ctrl => *scroll = (*scroll).min(max_scroll).saturating_sub(5),
            KeyCode::Char('d') if ctrl => *scroll = (*scroll).saturating_add(5).min(max_scroll),
            KeyCode::Char(c) if !ctrl => {
                // Insert at the caret and step over it.
                let byte = char_byte(input, *cursor);
                input.insert(byte, c);
                *cursor += 1;
            }
            _ => {}
        }
    }

    // ---- rendering -----------------------------------------------------

    fn draw(&self, frame: &mut Frame) {
        let [header, _, body, footer] = Layout::vertical([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .areas(frame.area());

        self.draw_header(frame, header);
        self.draw_footer(frame, footer);
        match &self.phase {
            Phase::Ask { .. } => self.draw_ask(frame, body),
            Phase::Summary => self.draw_summary(frame, body),
            _ => self.draw_card(frame, body),
        }
    }

    fn draw_header(&self, frame: &mut Frame, area: Rect) {
        let left = format!(
            " alix {} │ {}",
            env!("CARGO_PKG_VERSION"),
            self.options.deck_label
        );
        let h = self.session.stage_histogram(&self.store);
        // The remaining-card count lives in the footer now (bottom-right),
        // mirroring the web frontend; the header keeps just the stage histogram.
        // The stage bar. `hist_cells` dims stages above the top stage, but every
        // deck now reaches the top stage, so all five always show.
        let c = hist_cells(&h, self.session.top_stage());
        let right = format!("{}|{}|{}|{}|{}|{} ", c[0], c[1], c[2], c[3], c[4], c[5]);
        frame.render_widget(bar(&left, &right, area.width), area);
    }

    fn draw_footer(&self, frame: &mut Frame, area: Rect) {
        // A pending quit confirmation replaces the footer with the prompt.
        if self.confirming_quit {
            let n = self.session.remaining();
            let left = format!(
                " Quit? {n} card{} still queued — ENTER leave · any other key stays",
                if n == 1 { "" } else { "s" }
            );
            frame.render_widget(bar(&left, "", area.width), area);
            return;
        }
        let k = &self.options.keys;
        let l = Bindings::label;
        let keys = match &self.phase {
            Phase::Typing { .. } => {
                format!(
                    "{} hint │ {} skip │ {} remove │ {} leave",
                    l(&k.hint),
                    l(&k.skip),
                    l(&k.remove),
                    l(&k.quit)
                )
            }
            Phase::Fuzzy { .. } => format!(
                "{} submit line │ {} skip │ {} remove │ {} leave",
                l(&k.submit),
                l(&k.skip),
                l(&k.remove),
                l(&k.quit)
            ),
            Phase::Flip { revealed: false } => {
                format!(
                    "{} reveal │ {} skip │ {} remove │ {} leave",
                    l(&k.reveal),
                    l(&k.skip),
                    l(&k.remove),
                    l(&k.quit)
                )
            }
            Phase::Flip { revealed: true } => format!(
                "{} again │ {} good │ {} easy │ {} remove │ {} ask │ {} leave",
                l(&k.again),
                l(&k.good),
                l(&k.easy),
                l(&k.remove),
                l(&k.ask),
                l(&k.quit)
            ),
            Phase::Explain {
                revealed: false, ..
            } => format!(
                "ENTER reveal │ {} skip │ {} remove │ {} leave",
                l(&k.skip),
                l(&k.remove),
                l(&k.quit)
            ),
            Phase::Explain { revealed: true, .. } => format!(
                "{} again │ {} good │ {} easy │ {} remove │ {} ask │ {} leave",
                l(&k.again),
                l(&k.good),
                l(&k.easy),
                l(&k.remove),
                l(&k.ask),
                l(&k.quit)
            ),
            Phase::LineByLine { revealed } => {
                let total = self.session.current().map_or(0, |c| c.back.len());
                if *revealed < total {
                    format!(
                        "{} reveal next │ {} skip │ {} remove │ {} leave",
                        l(&k.reveal),
                        l(&k.skip),
                        l(&k.remove),
                        l(&k.quit)
                    )
                } else {
                    format!(
                        "{} again │ {} good │ {} easy │ {} remove │ {} ask │ {} leave",
                        l(&k.again),
                        l(&k.good),
                        l(&k.easy),
                        l(&k.remove),
                        l(&k.ask),
                        l(&k.quit)
                    )
                }
            }
            Phase::Choice {
                question,
                selected: None,
                ..
            } => {
                format!(
                    "1-{} select │ {} skip │ {} remove │ {} leave",
                    question.options.len(),
                    l(&k.skip),
                    l(&k.remove),
                    l(&k.quit)
                )
            }
            Phase::Choice {
                selected: Some(_), ..
            }
            | Phase::Feedback { .. } => {
                format!(
                    "{} continue │ {} ask │ {} leave",
                    l(&k.cont),
                    l(&k.ask),
                    l(&k.quit)
                )
            }
            Phase::Ask {
                waiting: Some(_), ..
            } => "thinking… │ ESC back".to_string(),
            Phase::Ask { .. } => format!(
                "ENTER send │ {} save note │ PgUp/PgDn scroll │ ESC back",
                l(&k.save_note)
            ),
            Phase::Summary if self.nothing_due => "any key to exit".to_string(),
            Phase::Summary => {
                let exam = if self.exam_due_decks().is_empty() {
                    ""
                } else {
                    "x take exam │ b browse │ "
                };
                format!(
                    "{exam}{} new session │ any other key to exit",
                    l(&k.restart)
                )
            }
        };
        let left = format!(" {keys}");
        // Passed / failed, then the remaining count with a ↓ arrow — same
        // layout as the web frontend's score line.
        let right = format!(
            "{}✓ {}✗ {}↓ ",
            self.session.stats.passed,
            self.session.stats.failed,
            self.session.remaining()
        );
        frame.render_widget(bar(&left, &right, area.width), area);
    }

    fn draw_card(&self, frame: &mut Frame, area: Rect) {
        let mut lines: Vec<Line> = Vec::new();
        let mut cursor: Option<(u16, u16)> = None;

        // During feedback (and an answered choice) the queue has already
        // advanced, so take the card from the phase.
        let card = match &self.phase {
            Phase::Feedback { card, .. } | Phase::Choice { card, .. } => card,
            _ => match self.session.current() {
                Some(card) => card,
                None => return,
            },
        };

        lines.push(Line::from(card.front.clone().bold()));
        // Cloze cards show their masked answer text below the front.
        for ctx in &card.context {
            lines.push(context_line(ctx));
        }
        lines.push(Line::default());

        // A mode badge at the top of the answer section — typing and fuzzy in
        // particular look identical without it (both are an input prompt).
        let mode_tag = match &self.phase {
            Phase::Typing { .. } => "TYPING EXACT",
            Phase::Fuzzy { .. } => "TYPING FUZZY",
            Phase::Flip { .. } => "FLIP",
            Phase::Explain { .. } => "EXPLAIN",
            Phase::LineByLine { .. } => "LINE BY LINE",
            Phase::Choice { .. } => "CHOICE",
            Phase::Feedback {
                mode: Mode::Fuzzy, ..
            } => "TYPING FUZZY",
            Phase::Feedback { .. } => "TYPING EXACT",
            _ => "",
        };
        if !mode_tag.is_empty() {
            lines.push(Line::from(mode_tag.dim()));
            lines.push(Line::default());
        }

        // A cited card with its source toggled on: the excerpt takes the answer's
        // place (swap, not stack), keeping the note + grade prompt below it. Done
        // as an early return so the normal per-mode render stays untouched.
        let answered = self.answered(card);
        let cited = card.at.is_some();
        if self.citation_view && answered && cited {
            self.push_source(&mut lines, card);
            self.push_answer_tail(&mut lines, card, area.width);
            self.push_citation_hint(&mut lines);
            frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area);
            return;
        }

        match &self.phase {
            Phase::Typing {
                claimed,
                done,
                current,
                hint,
                ..
            } => {
                // Already-completed rows, in entry order.
                for r in done {
                    let color = if r.passed { Color::Green } else { Color::Red };
                    lines.push(Line::from(vec![
                        Span::raw("> "),
                        Span::styled(r.input.clone(), Style::new().fg(color)),
                    ]));
                }
                // The row being typed, with per-character feedback and cursor.
                let mut spans = vec![Span::raw("> ")];
                let mut width = 2u16;
                for t in current.typed() {
                    let color = if t.correct { Color::Green } else { Color::Red };
                    spans.push(Span::styled(t.ch.to_string(), Style::new().fg(color)));
                    width += 1;
                }
                cursor = Some((area.x + width, area.y + lines.len() as u16));
                if let Some(hint) = hint {
                    spans.push(Span::styled(hint.clone(), Style::new().fg(Color::Yellow)));
                }
                lines.push(Line::from(spans));
                // Placeholder prompts for the remaining unclaimed lines (the one
                // being typed is already shown above).
                let remaining = claimed.iter().filter(|&&c| !c).count();
                for _ in 1..remaining {
                    lines.push(Line::from("> ".to_string()));
                }
            }
            Phase::Fuzzy { results, input } => {
                for r in results {
                    let color = if r.passed { Color::Green } else { Color::Red };
                    let mut spans = vec![
                        Span::raw("> "),
                        Span::styled(r.input.clone(), Style::new().fg(color)),
                    ];
                    // Show the exact answer whenever the input differed,
                    // even on a pass within tolerance.
                    if r.distance > 0 {
                        spans.push(Span::styled(
                            format!("  (expected: {})", r.expected),
                            Style::new().fg(Color::Yellow),
                        ));
                    }
                    lines.push(Line::from(spans));
                }
                if results.len() < card.back.len() {
                    cursor = Some((
                        area.x + 2 + input.chars().count() as u16,
                        area.y + lines.len() as u16,
                    ));
                    lines.push(Line::from(format!("> {input}")));
                }
            }
            Phase::Flip { revealed } => {
                if *revealed {
                    for back in &card.back {
                        lines.push(Line::from(Span::styled(
                            format!("  {back}"),
                            Style::new().fg(Color::Green),
                        )));
                    }
                    push_note(&mut lines, card, area.width);
                    lines.push(Line::default());
                    lines.push(Line::from("How well did you know it?".italic()));
                } else {
                    let reveal = Bindings::label(&self.options.keys.reveal);
                    lines.push(Line::from(
                        format!("[ press {reveal} to reveal the answer ]").dim(),
                    ));
                }
            }
            Phase::Explain { input, revealed } => {
                if *revealed {
                    // Your reconstruction (if any), then the points to compare it
                    // against, then self-grade.
                    if !input.is_empty() {
                        lines.push(Line::from("your answer:".dim()));
                        lines.push(Line::from(format!("  {input}")));
                        lines.push(Line::default());
                    }
                    lines.push(Line::from("your answer should cover:".dim()));
                    for point in &card.back {
                        lines.push(Line::from(Span::styled(
                            format!("  • {point}"),
                            Style::new().fg(Color::Green),
                        )));
                    }
                    push_note(&mut lines, card, area.width);
                    lines.push(Line::default());
                    lines.push(Line::from("How well did you cover them?".italic()));
                } else {
                    cursor = Some((
                        area.x + 2 + input.chars().count() as u16,
                        area.y + lines.len() as u16,
                    ));
                    lines.push(Line::from(format!("> {input}")));
                    lines.push(Line::default());
                    lines.push(Line::from(
                        "[ type your answer (optional), ENTER to reveal the points ]".dim(),
                    ));
                }
            }
            Phase::LineByLine { revealed } => {
                for back in card.back.iter().take(*revealed) {
                    lines.push(Line::from(Span::styled(
                        format!("  {back}"),
                        Style::new().fg(Color::Green),
                    )));
                }
                if *revealed < card.back.len() {
                    let reveal = Bindings::label(&self.options.keys.reveal);
                    lines.push(Line::from(
                        format!("[ press {reveal} to reveal the next line ]").dim(),
                    ));
                } else {
                    push_note(&mut lines, card, area.width);
                    lines.push(Line::default());
                    lines.push(Line::from("How well did you know it?".italic()));
                }
            }
            Phase::Choice {
                question, selected, ..
            } => {
                for (i, option) in question.options.iter().enumerate() {
                    let style = match selected {
                        None => Style::new(),
                        Some(_) if i == question.correct => Style::new().fg(Color::Green),
                        Some(s) if i == *s => Style::new().fg(Color::Red),
                        Some(_) => Style::new().fg(Color::DarkGray),
                    };
                    for (j, text) in option.lines().enumerate() {
                        let prefix = if j == 0 {
                            format!("  {}) ", i + 1)
                        } else {
                            "     ".into()
                        };
                        lines.push(Line::from(Span::styled(format!("{prefix}{text}"), style)));
                    }
                }
                if let Some(selected) = selected {
                    push_note(&mut lines, card, area.width);
                    lines.push(Line::default());
                    lines.push(if selected == &question.correct {
                        Line::from(" PASSED ".bold().fg(Color::Black).bg(Color::Green))
                    } else {
                        Line::from(" FAILED ".bold().fg(Color::Black).bg(Color::Red))
                    });
                }
            }
            Phase::Feedback {
                card,
                grade,
                mode,
                results,
            } => {
                for r in results {
                    let color = if r.passed { Color::Green } else { Color::Red };
                    lines.push(Line::from(vec![
                        Span::raw("> "),
                        Span::styled(r.input.clone(), Style::new().fg(color)),
                    ]));
                    // On a wrong line, show the correct answer underneath with a
                    // check mark so the right text — not the mistake — is what
                    // stays on screen.
                    if !r.passed {
                        let correction = match mode {
                            Mode::Fuzzy => format!("  (expected: {})", r.expected),
                            _ => format!("  ✓ {}", r.expected),
                        };
                        lines.push(Line::from(Span::styled(
                            correction,
                            Style::new().fg(Color::Green),
                        )));
                    }
                }
                push_note(&mut lines, card, area.width);
                lines.push(Line::default());
                lines.push(if grade.passed() {
                    Line::from(" PASSED ".bold().fg(Color::Black).bg(Color::Green))
                } else {
                    Line::from(" FAILED ".bold().fg(Color::Black).bg(Color::Red))
                });
            }
            Phase::Ask { .. } | Phase::Summary => unreachable!(),
        }

        // The answer-side affordance ( </> s view source ) under a cited card.
        if answered && cited {
            self.push_citation_hint(&mut lines);
        }

        let mut paragraph = Paragraph::new(lines);
        if cursor.is_none() {
            // Wrap long lines (notes, options) — but never while an input
            // cursor is shown, because wrapping would shift its position.
            paragraph = paragraph.wrap(Wrap { trim: false });
        }
        frame.render_widget(paragraph, area);
        if let Some((x, y)) = cursor {
            frame.set_cursor_position(Position::new(x, y));
        }
    }

    fn draw_ask(&self, frame: &mut Frame, area: Rect) {
        let Phase::Ask {
            card,
            transcript,
            input,
            cursor,
            waiting,
            scroll,
            status,
            ..
        } = &self.phase
        else {
            return;
        };

        let [content, input_area] =
            Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(area);

        // Compact card recap.
        let mut lines = vec![Line::from(card.front.clone().bold())];
        for ctx in &card.context {
            lines.push(context_line(ctx));
        }
        for back in &card.back {
            lines.push(Line::from(Span::styled(
                format!("> {back}"),
                Style::new().fg(Color::Green),
            )));
        }
        push_note(&mut lines, card, area.width);
        lines.push(Line::from("─── ask claude ───".dim()));
        lines.push(Line::default());

        for (question, answer) in transcript {
            lines.push(Line::from(
                format!("You: {question}").fg(Color::Cyan).bold(),
            ));
            lines.push(Line::default());
            for l in answer.lines() {
                lines.push(Line::from(l.to_string()));
            }
            lines.push(Line::default());
        }

        if waiting.is_some() {
            lines.push(Line::from(
                format!("Claude is thinking {}", spinner()).italic().dim(),
            ));
        }
        if let Some(status) = status {
            lines.push(Line::from(Span::styled(
                status.clone(),
                Style::new().fg(Color::Yellow),
            )));
        }

        // Scroll the transcript; remember the maximum so the key handler
        // can clamp paging. The wrapped height is estimated conservatively
        // (word wrap may break lines a bit earlier than the full width).
        let usable = content.width.saturating_sub(5).max(1) as usize;
        let total: usize = lines
            .iter()
            .map(|line| line.width().div_ceil(usable).max(1))
            .sum();
        let max_scroll = (total as u16).saturating_sub(content.height);
        let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
        self.ask_max_scroll.set(max_scroll);
        frame.render_widget(paragraph.scroll(((*scroll).min(max_scroll), 0)), content);

        // The input line. Scroll horizontally so the caret stays visible when
        // the question outgrows the width: keep it at the right edge once it
        // moves past `visible`, otherwise show from the start.
        let visible = (input_area.width as usize).saturating_sub(3);
        let offset = cursor.saturating_sub(visible);
        let shown: String = input.chars().skip(offset).take(visible).collect();
        frame.render_widget(Paragraph::new(format!("> {shown}")), input_area);
        if waiting.is_none() {
            frame.set_cursor_position(Position::new(
                input_area.x + 2 + (cursor - offset) as u16,
                input_area.y,
            ));
        }
    }

    fn draw_summary(&self, frame: &mut Frame, area: Rect) {
        let stats = self.session.stats;
        let accuracy = if stats.reviews > 0 {
            format!("{:.0}%", 100.0 * stats.passed as f64 / stats.reviews as f64)
        } else {
            "-".to_string()
        };
        let h = self.session.stage_histogram(&self.store);

        // The stage bar (stages above the top would dim, but every deck now
        // reaches the top stage).
        let top = self.session.top_stage();
        let mut stage_spans = vec![Span::raw(format!("  stages:   new {} │", h[0]))];
        for s in 1..=5u8 {
            if s > top {
                stage_spans.push(Span::styled(
                    format!(" s{s} –"),
                    Style::new().fg(Color::DarkGray),
                ));
            } else {
                stage_spans.push(Span::raw(format!(" s{s} {}", h[s as usize])));
            }
            if s < 5 {
                stage_spans.push(Span::raw(" │"));
            }
        }

        let mut lines = vec![
            Line::from("Session complete!".bold()),
            Line::default(),
            Line::from(format!(
                "  reviews:  {} ({} passed, {} failed)",
                stats.reviews, stats.passed, stats.failed
            )),
            Line::from(format!("  accuracy: {accuracy}")),
            Line::default(),
            Line::from(stage_spans),
        ];

        if self.nothing_due {
            lines.push(Line::default());
            let now = time::now_ms();
            let next = self
                .session
                .next_due_at(&self.store)
                .filter(|&due| due > now)
                .map(|due| format!(" — next card in {}", time::humanize_ms(due - now)))
                .unwrap_or_default();
            lines.push(Line::from(
                format!("  Nothing due right now{next}.").fg(Color::Yellow),
            ));
        }
        // Decks that became exam-due this session: offer the exam (press `x`).
        for (subject, _) in self.exam_due_decks() {
            lines.push(Line::default());
            lines.push(Line::from(
                format!(
                    "  ✦ {subject} is ready for its exam — press x to take it, or b to browse."
                )
                .fg(Color::Yellow),
            ));
        }
        frame.render_widget(Paragraph::new(lines), area);
    }
}

/// Converts a crossterm key event into a bindable [`KeyPattern`]. Keys we
/// don't support binding (function keys, arrows, ...) yield `None`.
pub(crate) fn key_pattern(key: &KeyEvent) -> Option<KeyPattern> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let k = match key.code {
        KeyCode::Char(c) => Key::Char(c),
        KeyCode::Enter => Key::Enter,
        KeyCode::Tab => Key::Tab,
        KeyCode::Esc => Key::Esc,
        KeyCode::Backspace => Key::Backspace,
        _ => return None,
    };
    Some(KeyPattern { key: k, ctrl })
}

/// A spinner frame derived from the wall clock (the event loop redraws
/// every ~100ms while a CLI call is pending).
fn spinner() -> char {
    const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
    FRAMES[(time::now_ms() / 100) as usize % FRAMES.len()]
}

/// Renders a full-width colored bar with left- and right-aligned text.
pub(crate) fn bar(left: &str, right: &str, width: u16) -> Paragraph<'static> {
    let pad = (width as usize)
        .saturating_sub(left.chars().count())
        .saturating_sub(right.chars().count());
    let text = format!("{left}{}{right}", " ".repeat(pad));
    Paragraph::new(text).style(HEADER_STYLE)
}

/// The PASSED / FAILED badge shown after a graded card (typing/fuzzy feedback,
/// an answered choice), shared by the normal and source-view renders.
fn passed_failed_badge(passed: bool) -> Line<'static> {
    if passed {
        Line::from(" PASSED ".bold().fg(Color::Black).bg(Color::Green))
    } else {
        Line::from(" FAILED ".bold().fg(Color::Black).bg(Color::Red))
    }
}

/// Appends the card's note, if any, as a yellow quoted block with a left bar.
/// The note's structure (sentence-split prose, verbatim code blocks) comes
/// from [`render::note_units`]; this function only paints it: each unit is
/// separated by a blank bar line, prose is word-wrapped to the width and
/// styled yellow, and code is rendered gray and verbatim.
pub(crate) fn push_note(lines: &mut Vec<Line>, card: &Card, width: u16) {
    let units = render::note_units(card);
    if units.is_empty() {
        return;
    }
    lines.push(Line::default());
    const GUTTER: &str = "  │ ";
    const BAR: &str = "  │"; // gutter without the trailing space, for blanks
    let bar_style = Style::new().fg(Color::Yellow);
    let text_width = (width as usize).saturating_sub(GUTTER.chars().count());

    for (i, unit) in units.iter().enumerate() {
        // One blank bar line between consecutive units, none before the first.
        if i > 0 {
            lines.push(Line::from(Span::styled(BAR, bar_style)));
        }
        match unit {
            NoteUnit::Sentence(sentence) => {
                for row in render::wrap_text(sentence, text_width) {
                    lines.push(Line::from(vec![
                        Span::styled(GUTTER, bar_style),
                        Span::styled(row, bar_style),
                    ]));
                }
            }
            NoteUnit::Code(code) => {
                for line in code {
                    lines.push(Line::from(vec![
                        Span::styled(GUTTER, bar_style),
                        Span::styled(line.clone(), Style::new().fg(Color::Gray)),
                    ]));
                }
            }
        }
    }
}

/// Builds the styled line for a cloze context string (indented two spaces):
/// the active blank is bright and bold, hidden sibling holes are dim, the rest
/// is cyan — matching the web frontend.
pub(crate) fn context_line(ctx: &str) -> Line<'static> {
    let mut spans = vec![Span::raw("  ")];
    for seg in render::context_spans(ctx) {
        let (text, style) = match seg {
            ContextSpan::Text(t) => (t, Style::new().fg(Color::Cyan)),
            ContextSpan::Blank(t) => (
                t,
                Style::new()
                    .fg(Color::LightCyan)
                    .add_modifier(Modifier::BOLD),
            ),
            ContextSpan::Hidden(t) => (t, Style::new().fg(Color::DarkGray)),
        };
        spans.push(Span::styled(text, style));
    }
    Line::from(spans)
}

/// The six stage-histogram cells (new, s1..s5) as strings, dimming stages above
/// `top_stage` to `–`. Every deck now reaches the top stage, so in practice all
/// five render.
fn hist_cells(h: &[usize; 6], top_stage: u8) -> [String; 6] {
    std::array::from_fn(|i| {
        if i >= 1 && i as u8 > top_stage {
            "–".to_string()
        } else {
            h[i].to_string()
        }
    })
}

/// Points the current typing row at whichever still-unclaimed expected line it
/// best matches as a prefix, so its characters are colored against a concrete
/// target. With a single answer line this always picks that line; with several
/// it lets the user type the items in any order.
fn retarget(current: &mut TypingValidator, expected: &[String], claimed: &[bool]) {
    let typed: String = current.typed().iter().map(|t| t.ch).collect();
    let candidates: Vec<&str> = expected
        .iter()
        .enumerate()
        .filter(|(i, _)| !claimed[*i])
        .map(|(_, e)| e.as_str())
        .collect();
    if let Some(rel) = best_prefix_match(&typed, &candidates) {
        current.set_expected(candidates[rel]);
    }
}

/// Builds a feedback line for a completed typing-mode line from its validator:
/// the text the user typed, the expected text, and whether it passed (a line
/// completed without a hint). `distance` is only a pass/fail flag here.
fn typing_result(v: &TypingValidator) -> FuzzyResult {
    let input: String = v.typed().iter().map(|t| t.ch).collect();
    let passed = v.passed();
    FuzzyResult {
        input,
        expected: v.expected(),
        distance: usize::from(!passed),
        passed,
    }
}

/// Byte offset of the `n`th character in `s`, or `s.len()` if `n` is at or
/// past the end. Lets a character-based caret edit a UTF-8 string safely.
fn char_byte(s: &str, n: usize) -> usize {
    s.char_indices().nth(n).map_or(s.len(), |(b, _)| b)
}

// ── AI exam (interactive TUI) ────────────────────────────────────────────────

/// The interactive exam TUI: a sibling of [`App`] that drives one
/// [`exam::Sitting`] (generate → answer one question at a time → grade →
/// results → remediate). It reuses the same background-poll loop and free-text
/// input as review; the deck's mechanical review stays in [`App`].
pub struct ExamApp {
    sitting: exam::Sitting,
    store: Store,
    /// The deck under exam (for resolving what a pass unlocks).
    deck_path: PathBuf,
    decks_dir: Option<PathBuf>,
    /// Scroll offset of the results breakdown.
    scroll: u16,
    quit: bool,
}

impl ExamApp {
    /// Starts an exam for `deck` (the caller has checked it declares a
    /// `% source:` and is drilled). Question generation spawns immediately.
    pub fn new(
        deck: Deck,
        strictness: Strictness,
        exam_cfg: ExamConfig,
        ask_cfg: AskConfig,
        store: Store,
        decks_dir: Option<PathBuf>,
    ) -> Self {
        let deck_path = deck.path.clone();
        let sitting = exam::Sitting::start(&deck, strictness, exam_cfg, ask_cfg);
        Self {
            sitting,
            store,
            deck_path,
            decks_dir,
            scroll: 0,
            quit: false,
        }
    }

    /// Runs the exam TUI until the user leaves. The store is saved (the sitting
    /// also persists "mastered" the moment a pass is graded).
    pub fn run(mut self) -> Result<()> {
        let mut terminal = ratatui::init();
        let result = self.event_loop(&mut terminal);
        ratatui::restore();
        let _ = self.store.save();
        result
    }

    /// Like [`run`](Self::run) but on a caller-owned `terminal` (no init/restore),
    /// so an exam launched from the picker resumes it afterwards seamlessly.
    pub fn run_on(mut self, terminal: &mut ratatui::DefaultTerminal) -> Result<()> {
        let result = self.event_loop(terminal);
        let _ = self.store.save();
        result
    }

    fn event_loop(&mut self, terminal: &mut ratatui::DefaultTerminal) -> Result<()> {
        while !self.quit {
            terminal.draw(|frame| self.draw(frame))?;
            // Poll so the spinner animates and background calls land while no
            // key is pressed.
            if event::poll(Duration::from_millis(100))? {
                match event::read()? {
                    Event::Resize(w, h) => terminal.resize(Rect::new(0, 0, w, h))?,
                    Event::Key(key) if key.kind == KeyEventKind::Press => self.handle_key(key),
                    _ => {}
                }
            }
            // On a phase transition, reset the scroll so a fresh error banner
            // (or a new result) starts in view rather than scrolled past.
            if self.sitting.poll(&mut self.store, time::now_ms()) {
                self.scroll = 0;
            }
        }
        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match self.sitting.phase() {
            exam::Phase::Answering => match key.code {
                KeyCode::Esc => self.quit = true,
                // Tab walks forward; on the last question it submits for grading.
                KeyCode::Tab => {
                    if self.sitting.on_last() {
                        self.sitting.submit();
                    } else {
                        self.sitting.next();
                    }
                }
                KeyCode::BackTab => self.sitting.prev(),
                KeyCode::Enter => self.sitting.push_char('\n'),
                KeyCode::Backspace if !ctrl => self.sitting.pop_char(),
                KeyCode::Char(c) if !ctrl => self.sitting.push_char(c),
                _ => {}
            },
            exam::Phase::Results => match key.code {
                KeyCode::Esc | KeyCode::Enter => self.quit = true,
                KeyCode::Char('r') if self.sitting.can_remediate() => self.sitting.remediate(),
                KeyCode::Down | KeyCode::Char('j') => self.scroll = self.scroll.saturating_add(1),
                KeyCode::Up | KeyCode::Char('k') => self.scroll = self.scroll.saturating_sub(1),
                _ => {}
            },
            exam::Phase::Remediated => {
                if matches!(key.code, KeyCode::Esc | KeyCode::Enter) {
                    self.quit = true;
                }
            }
            // Generating / Grading / Remediating: only Esc leaves.
            _ => {
                if key.code == KeyCode::Esc {
                    self.quit = true;
                }
            }
        }
    }

    fn draw(&self, frame: &mut Frame) {
        let [header, _, body, footer] = Layout::vertical([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .areas(frame.area());

        let left = format!(
            " alix {} │ exam · {}",
            env!("CARGO_PKG_VERSION"),
            self.sitting.subject()
        );
        let right = format!("{} ", exam_strictness_label(self.sitting.strictness()));
        frame.render_widget(bar(&left, &right, header.width), header);
        self.draw_footer(frame, footer);
        self.draw_body(frame, body);
    }

    fn draw_footer(&self, frame: &mut Frame, area: Rect) {
        let keys = match self.sitting.phase() {
            exam::Phase::Answering if self.sitting.on_last() => {
                "TAB submit for grading │ SHIFT-TAB back │ ESC quit"
            }
            exam::Phase::Answering => "TAB next │ SHIFT-TAB back │ ESC quit",
            exam::Phase::Results if self.sitting.can_remediate() => {
                "R add remediation cards │ ↑/↓ scroll │ ESC close"
            }
            exam::Phase::Results => "↑/↓ scroll │ ESC close",
            exam::Phase::Remediated => "ESC close",
            _ => "ESC cancel",
        };
        frame.render_widget(bar(&format!(" {keys}"), "", area.width), area);
    }

    fn draw_body(&self, frame: &mut Frame, area: Rect) {
        let mut lines: Vec<Line> = Vec::new();
        // A failed background call surfaces a prominent banner at the top, so a
        // long grade list below can't push it out of view.
        if let Some(e) = self.sitting.error() {
            lines.push(Line::from(format!("⚠ {e}").bold().fg(Color::Red)));
            lines.push(Line::default());
        }
        match self.sitting.phase() {
            exam::Phase::Generating | exam::Phase::Grading | exam::Phase::Remediating => {
                let msg = match self.sitting.phase() {
                    exam::Phase::Grading => "Grading your answers…",
                    exam::Phase::Remediating => "Writing remediation cards…",
                    _ => "Preparing your exam…",
                };
                if self.sitting.thinking() {
                    let elapsed = self
                        .sitting
                        .elapsed_secs()
                        .map(|s| format!("  ({s}s — Claude is working)"))
                        .unwrap_or_default();
                    lines.push(Line::from(format!("{} {msg}{elapsed}", spinner())));
                } else {
                    // Not thinking in a spinner phase means the call failed; the
                    // error banner is shown above.
                    lines.push(Line::from("The exam helper could not complete.".dim()));
                }
            }
            exam::Phase::Answering => {
                lines.push(Line::from(
                    format!(
                        "Question {} / {}",
                        self.sitting.current_index() + 1,
                        self.sitting.total()
                    )
                    .dim(),
                ));
                lines.push(Line::default());
                if let Some(q) = self.sitting.question() {
                    lines.push(Line::from(q.prompt.clone().bold()));
                }
                lines.push(Line::default());
                // The answer so far, with a block cursor at the end.
                let answer = self.sitting.answer();
                let shown = format!("{answer}▌");
                for (i, l) in shown.split('\n').enumerate() {
                    lines.push(Line::from(if i == 0 {
                        format!("> {l}")
                    } else {
                        format!("  {l}")
                    }));
                }
                lines.push(Line::default());
                lines.push(Line::from(
                    "(type your answer — ENTER for a new line)".dim(),
                ));
            }
            exam::Phase::Results => {
                if let Some(r) = self.sitting.result() {
                    if r.passed {
                        lines.push(Line::from(
                            "PASSED — deck mastered ✓".bold().fg(Color::Green),
                        ));
                        let unlocks = self.unlocks();
                        if !unlocks.is_empty() {
                            lines.push(Line::from(
                                format!("Unlocks: {}", unlocks.join(", ")).fg(Color::Green),
                            ));
                        }
                    } else {
                        lines.push(Line::from("FAILED".bold().fg(Color::Red)));
                    }
                    lines.push(Line::default());
                    for (i, (q, g)) in self.sitting.questions().iter().zip(&r.grades).enumerate() {
                        lines.push(Line::from(format!("Q{}. {}", i + 1, q.prompt)));
                        let color = match g.verdict {
                            exam::Verdict::Pass => Color::Green,
                            exam::Verdict::Partial => Color::Yellow,
                            exam::Verdict::Fail => Color::Red,
                        };
                        lines.push(Line::from(
                            format!("  {} — {}", g.verdict.label(), g.feedback).fg(color),
                        ));
                        if g.verdict != exam::Verdict::Pass {
                            if !q.points.is_empty() {
                                lines.push(Line::from("  a complete answer covers:".dim()));
                                for p in &q.points {
                                    lines.push(Line::from(format!("    • {p}")));
                                }
                            }
                            for m in &g.missed {
                                lines.push(Line::from(format!("    ✗ {m}").fg(Color::Red)));
                            }
                        }
                        lines.push(Line::default());
                    }
                }
            }
            exam::Phase::Remediated => {
                lines.push(Line::from("Remediation cards added ✓".fg(Color::Green)));
                lines.push(Line::default());
                lines.push(Line::from("Re-drill the deck, then re-sit the exam."));
            }
        }
        let scroll = if matches!(self.sitting.phase(), exam::Phase::Results) {
            self.scroll
        } else {
            0
        };
        let paragraph = Paragraph::new(lines)
            .wrap(Wrap { trim: false })
            .scroll((scroll, 0));
        frame.render_widget(paragraph, area);
    }

    /// Decks a pass unlocks (those that `% requires:` this one).
    fn unlocks(&self) -> Vec<String> {
        match &self.decks_dir {
            Some(dir) => deck::dependents(&self.deck_path, dir),
            None => Vec::new(),
        }
    }
}

fn exam_strictness_label(s: Strictness) -> &'static str {
    match s {
        Strictness::Strict => "strict",
        Strictness::Balanced => "balanced",
        Strictness::Lenient => "lenient",
    }
}

#[cfg(test)]
mod tests {
    use super::char_byte;

    #[test]
    fn char_byte_maps_caret_to_utf8_offset() {
        // ASCII: caret index equals byte offset.
        assert_eq!(char_byte("hello", 0), 0);
        assert_eq!(char_byte("hello", 3), 3);
        // Past the end clamps to the byte length (append position).
        assert_eq!(char_byte("hello", 9), 5);
        // Multi-byte chars: the 'é' is two bytes, so later carets shift.
        assert_eq!(char_byte("héllo", 1), 1);
        assert_eq!(char_byte("héllo", 2), 3);
        assert_eq!(char_byte("héllo", 5), 6);
    }
}