alix 0.8.0

A learning tool 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
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
use serde::{Deserialize, Serialize};

use crate::{
    answer::{self, Input, Mode},
    augment::AugmentCache,
    card::{AnswerSpace, Card},
    choice::{self, ChoiceQuestion},
    depth::{self, Depth},
    inline::{DisplayProjector, InlineRun},
    render::{self, ContentUnit},
    session::{self, Session},
    store::Store,
};

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RegionRole {
    /// A region THIS card asks: masked until answered, then revealed.
    Asked,
    /// Another card's blank on the same media: masked, never revealed here.
    Mask,
    /// A cover: masked while its content could give an answer away; whether
    /// it reveals on answer travels in `reveal_on_answer`, never in the role.
    Cover,
}

/// One drawable region (ADR 0034). Geometry is JSON numbers in the unit the
/// author wrote.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct RegionView {
    pub role: RegionRole,
    /// Whether local answer reveal unmasks this region: an asked blank and a
    /// plain card's cover do, a sibling mask and a region card's cover never
    /// do. Carried per region because the role alone cannot say (ADR 0034,
    /// cover reveal split).
    pub reveal_on_answer: bool,
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    /// `"px"` or `"%"`, one per region by the per-media unit law.
    pub unit: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CropView {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub unit: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ImageView {
    pub src: String,
    pub alt: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub regions: Vec<RegionView>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crop: Option<CropView>,
}

/// One note as a client renders it: its badge, when a blockquote opened it,
/// and the display units of its body.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NoteView {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub badge: Option<crate::card::Badge>,
    pub units: Vec<ContentUnit>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CardView {
    pub front: String,
    #[serde(default)]
    pub front_runs: Vec<InlineRun>,
    #[serde(default)]
    pub front_units: Option<Vec<ContentUnit>>,
    /// The card's section: its `# ` heading and that section's prose, shown
    /// only on demand. Image syntax inside it stays prose.
    #[serde(default)]
    pub section_context: Vec<String>,
    #[serde(default)]
    pub section_context_runs: Vec<Vec<InlineRun>>,
    /// Fence-shaped units only, in fence order, exactly as `context_units`.
    #[serde(default)]
    pub section_context_units: Vec<ContentUnit>,
    pub context: Vec<String>,
    #[serde(default)]
    pub context_leads: bool,
    #[serde(default)]
    pub context_runs: Vec<Vec<InlineRun>>,
    /// The context's fence-shaped units only, in fence order (the nth raw
    /// fence consumes the nth unit); context prose keeps its line rendering.
    #[serde(default)]
    pub context_units: Vec<ContentUnit>,
    pub back: Vec<String>,
    #[serde(default)]
    pub back_runs: Vec<Vec<InlineRun>>,
    #[serde(default)]
    pub back_units: Vec<ContentUnit>,
    /// The steps a client walks the answer in: one per gradeable line, one
    /// per quotation run. Reveal counts every step; typing counts only the
    /// gradeable ones.
    #[serde(default)]
    pub answer_steps: Vec<crate::render::AnswerStep>,
    pub reshaped: bool,
    pub note: Vec<NoteView>,
    pub images: Vec<ImageView>,
    pub images_back: Vec<ImageView>,
    pub citations: Vec<String>,
}

fn image_views(
    images: &[crate::card::CardImage],
    asked: &dyn Fn(Option<&str>) -> bool,
    covers_reveal: bool,
) -> Vec<ImageView> {
    use crate::parser::region::{RegionGeometry, RegionKind};
    let unit = |percent: bool| if percent { "%" } else { "px" }.to_string();
    images
        .iter()
        .map(|image| ImageView {
            src: image.src.display().to_string(),
            alt: image.alt.clone(),
            regions: image
                .regions
                .iter()
                .filter_map(|region| {
                    let RegionGeometry::Rect {
                        x,
                        y,
                        width,
                        height,
                    } = &region.geometry
                    else {
                        return None;
                    };
                    let role = match region.kind {
                        RegionKind::Cover => RegionRole::Cover,
                        RegionKind::Blank if asked(region.stamp.as_deref()) => RegionRole::Asked,
                        RegionKind::Blank => RegionRole::Mask,
                    };
                    let reveal_on_answer = match role {
                        RegionRole::Asked => true,
                        RegionRole::Mask => false,
                        RegionRole::Cover => covers_reveal,
                    };
                    Some(RegionView {
                        role,
                        reveal_on_answer,
                        x: x.value,
                        y: y.value,
                        width: width.value,
                        height: height.value,
                        unit: unit(x.percent),
                    })
                })
                .collect(),
            crop: image.crop.as_ref().map(|crop| CropView {
                x: crop.x.value,
                y: crop.y.value,
                width: crop.width.value,
                height: crop.height.value,
                unit: unit(crop.x.percent),
            }),
        })
        .collect()
}

/// A cover reveals with the answer only on a card whose block poses no
/// sibling questions the cover could give away: neither a region card nor a
/// cloze sub-card.
pub(crate) fn covers_reveal(card: &Card) -> bool {
    !card.is_blank_card()
}

/// Which stamps the projected card asks: a single region's own stamp, a
/// group's member stamps, and none for an ordinary card.
fn asked_stamps(card: &Card) -> Vec<std::sync::Arc<str>> {
    match &card.region {
        None => Vec::new(),
        Some(crate::card::RegionSlot::Single { stamp, .. }) => stamp.iter().cloned().collect(),
        Some(crate::card::RegionSlot::Group { members, .. }) => {
            members.iter().filter_map(|m| m.stamp.clone()).collect()
        }
    }
}

impl From<&Card> for CardView {
    fn from(card: &Card) -> Self {
        let mut projector = DisplayProjector::default();
        CardView::project(card, &mut projector)
    }
}

impl CardView {
    pub fn project(card: &Card, projector: &mut DisplayProjector) -> Self {
        Self::project_in(card, projector, AnswerSpace::Displayed)
    }

    /// One card, served in ONE answer space. Every answer-bearing field moves
    /// together: a typed check grades what it serves, so serving a reshape it
    /// does not grade is what let an unvalidated model relabel become the
    /// exact target (Codex, 2026-08-25).
    pub fn project_in(card: &Card, projector: &mut DisplayProjector, space: AnswerSpace) -> Self {
        projector.set_definitions(card.definitions.clone());
        let (front, front_runs) = project_block(&card.front, projector);
        let front_units = render::front_units_with(&card.front, projector, &card.resolved_diagrams);
        let context_runs = card
            .context
            .iter()
            .map(|line| projector.project_context(line))
            .collect();
        let lines = card.answer_lines(space);
        let (back, back_runs) = project_lines(lines, projector);
        let back_units = render::answer_units_with(lines, projector, &card.resolved_diagrams);
        let answer_steps = render::card_answer_steps(card, projector, space);
        let section_context_runs = card
            .section_context
            .iter()
            .map(|line| projector.project_context(line))
            .collect();
        CardView {
            front,
            front_runs,
            front_units,
            section_context: card.section_context.clone(),
            section_context_runs,
            section_context_units: render::section_units(&card.section_context),
            context: card.context.clone(),
            context_leads: card.context_leads,
            context_runs,
            context_units: render::context_units_with(card),
            back,
            back_runs,
            back_units,
            answer_steps,
            reshaped: space == AnswerSpace::Displayed && card.display_back.is_some(),
            note: render::note_views_with(card, projector),
            images: {
                let stamps = asked_stamps(card);
                let asked = move |stamp: Option<&str>| {
                    stamp.is_some_and(|s| stamps.iter().any(|a| a.as_ref() == s))
                };
                image_views(&card.images, &asked, covers_reveal(card))
            },
            images_back: {
                let stamps = asked_stamps(card);
                let asked = move |stamp: Option<&str>| {
                    stamp.is_some_and(|s| stamps.iter().any(|a| a.as_ref() == s))
                };
                image_views(&card.images_back, &asked, covers_reveal(card))
            },
            citations: card
                .citations
                .iter()
                .map(|citation| citation.locator.clone())
                .collect(),
        }
    }
}

fn project_block(text: &str, projector: &mut DisplayProjector) -> (String, Vec<InlineRun>) {
    let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
    let (content_lines, line_runs) = project_lines(&lines, projector);
    let mut runs = Vec::new();
    for (index, mut projected) in line_runs.into_iter().enumerate() {
        if index > 0 {
            runs.push(InlineRun {
                text: "\n".to_string(),
                ..InlineRun::default()
            });
        }
        runs.append(&mut projected);
    }
    (content_lines.join("\n"), runs)
}

fn project_lines(
    lines: &[String],
    projector: &mut DisplayProjector,
) -> (Vec<String>, Vec<Vec<InlineRun>>) {
    let mut content = Vec::with_capacity(lines.len());
    let mut display = Vec::with_capacity(lines.len());
    let mut code_fence: Option<(char, usize)> = None;
    for line in lines {
        let marker = fence_marker(line);
        let fence = match code_fence {
            None => marker.is_some(),
            Some((open, len)) => crate::parser::closes_fence(line.trim_start(), open, len),
        };
        let runs = if code_fence.is_some() || fence {
            literal_runs(line)
        } else {
            projector.project(line)
        };
        content.push(runs.iter().map(|run| run.text.as_str()).collect());
        display.push(runs);
        if fence {
            code_fence = if code_fence.is_some() { None } else { marker };
        }
    }
    (content, display)
}

fn fence_marker(line: &str) -> Option<(char, usize)> {
    let trimmed = line.trim_start();
    let ch = if trimmed.starts_with("```") {
        '`'
    } else if trimmed.starts_with("~~~") {
        '~'
    } else {
        return None;
    };
    Some((ch, trimmed.chars().take_while(|c| *c == ch).count()))
}

fn literal_runs(text: &str) -> Vec<InlineRun> {
    if text.is_empty() {
        Vec::new()
    } else {
        vec![InlineRun {
            text: text.to_string(),
            ..InlineRun::default()
        }]
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ReviewState {
    pub card: Option<CardView>,
    pub mode: Mode,
    pub depth: Depth,
    pub introducing: bool,
    /// The correct index is deliberately absent here: it only travels in
    /// [`ChoiceFeedback`], so this payload can never leak the answer.
    pub choices: Option<Vec<String>>,
    /// `Some(true)` when the served pick is select-all-that-apply
    /// (`choices: multiple`); absent on a single pick and off `choice` mode.
    #[serde(default)]
    pub choices_multiple: Option<bool>,
    #[serde(default)]
    pub choice_runs: Option<Vec<Vec<InlineRun>>>,
    pub keypoints: Option<Vec<String>>,
    #[serde(default)]
    pub keypoint_runs: Option<Vec<Vec<InlineRun>>>,
    pub input: Input,
    pub finished: bool,
    pub remaining: u32,
    pub initial: u32,
    pub reviews: u32,
    pub passed: u32,
    pub failed: u32,
    // Distinguishes an introduction-only sitting: without it, a first pass over a
    // fresh deck reads as "reviewed 0".
    pub introduced: u32,
    pub partial: u32,
    pub can_restart: bool,
    pub next_due_ms: Option<u64>,
    // The uncapped backlog beyond this sitting, populated only at done: how many
    // due (or met-but-unrecognized) and never-met cards a chained sitting would
    // still find.
    pub due_left: u32,
    pub new_left: u32,
    // Deck-wide lifetime standing, populated only at done: how many of the
    // deck's cards have ever been met, out of how many it holds.
    pub met_total: u32,
    pub deck_total: u32,
    /// Present only on an exhausted Recognize done: what the depth filter hid,
    /// so the summary can point at Recall or at augmenting instead of at
    /// nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recognize_gap: Option<session::RecognizeGap>,
    /// A failed progress save, kept until one succeeds; review continues in
    /// memory (non-fatal, mirroring the serve loop's banner semantics). The
    /// builder leaves it `None`; a stateful caller stamps it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub save_error: Option<String>,
    /// Deck-load diagnostics (a stamped diagram that did not resolve). The
    /// builder leaves it empty; a stateful caller stamps it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub load_warnings: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChoiceFeedback {
    pub chosen: usize,
    pub correct: usize,
    pub passed: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MultiChoiceFeedback {
    pub chosen: Vec<usize>,
    pub correct: Vec<usize>,
    pub passed: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CheckFeedback {
    pub results: Vec<answer::TypedResult>,
    pub passed: bool,
}

pub fn state(
    session: &Session,
    store: &Store,
    augment: &AugmentCache,
    now_ms: Option<u64>,
) -> ReviewState {
    let now = now_ms.unwrap_or_else(session::now_ms);
    let card = session.current();
    let depth = session.depth();
    let base_mode = card
        .map(|c| depth::check_for(c.reveal.unwrap_or_default(), depth, c))
        .unwrap_or_default();
    let introducing = session.current_fresh(store);
    let question = current_question(session, store, augment);
    let choices_multiple = question
        .as_ref()
        .is_some_and(|q| q.multiple)
        .then_some(true);
    let choices = question.map(|q| q.options);
    // Falls back to Flip when no pick can be built (no distractors): claiming
    // a choice with nothing to choose would strand the card.
    let mode = if base_mode == Mode::Choice && choices.is_none() {
        Mode::Flip
    } else {
        base_mode
    };
    // Falls back to the card's AUTHORED claims, never the reshaped
    // display_back and never a supporting quotation, so the checklist rubric
    // stays truthful.
    let keypoints = if !introducing && mode == Mode::Explain {
        card.map(|c| {
            c.id()
                .and_then(|id| {
                    augment
                        .keypoints(&id, c.content_fingerprint)
                        .map(<[String]>::to_vec)
                })
                .unwrap_or_else(|| crate::render::gradeable_answer_lines(c, AnswerSpace::Authored))
        })
    } else {
        None
    };
    let mut projector = DisplayProjector::default();
    let space = if mode.is_typed() {
        AnswerSpace::Authored
    } else {
        AnswerSpace::Displayed
    };
    let card_view = card.map(|card| CardView::project_in(card, &mut projector, space));
    let choice_runs = choices.as_ref().map(|choices| {
        choices
            .iter()
            .map(|choice| projector.project(choice))
            .collect()
    });
    let keypoint_runs = keypoints.as_ref().map(|keypoints| {
        keypoints
            .iter()
            .map(|keypoint| projector.project(keypoint))
            .collect()
    });
    let finished = session.is_finished();
    // Only the done screen reads the backlog split, and it re-scans every card,
    // so keep it off the live path.
    let (due_left, new_left) = if finished {
        session.remaining_split(store, now)
    } else {
        (0, 0)
    };
    let (met_total, deck_total) = if finished {
        session.deck_progress(store)
    } else {
        (0, 0)
    };
    ReviewState {
        card: card_view,
        mode,
        depth,
        introducing,
        choices,
        choices_multiple,
        choice_runs,
        keypoints,
        keypoint_runs,
        // Last in the chain, after the card's own directive and the deck's:
        // the rule fills a gap and never overrules what an author wrote.
        input: card.and_then(|c| c.input).unwrap_or_default(),
        finished,
        remaining: session.remaining() as u32,
        initial: session.initial_size as u32,
        reviews: session.stats.reviews as u32,
        passed: session.stats.passed as u32,
        failed: session.stats.failed as u32,
        introduced: session.stats.introduced as u32,
        partial: session.stats.partial as u32,
        can_restart: session.has_due_now(store, now),
        // Both scopes, since a card met in an earlier sitting is not in this
        // roster and can open well before anything this sitting cooled.
        next_due_ms: finished
            .then(|| {
                [
                    session.next_servable_at(store, now),
                    session.next_due_at(store),
                ]
                .into_iter()
                .flatten()
                .filter(|&t| t > now)
                .min()
            })
            .flatten(),
        due_left: due_left as u32,
        new_left: new_left as u32,
        met_total: met_total as u32,
        deck_total: deck_total as u32,
        recognize_gap: finished
            .then(|| session.recognize_gap(store, now))
            .flatten(),
        save_error: None,
        load_warnings: Vec::new(),
    }
}

// The single place a question is built: `state`'s options and `choose`'s
// correct index must both come from here, or they drift out of lockstep.
pub fn current_question(
    session: &Session,
    store: &Store,
    augment: &AugmentCache,
) -> Option<ChoiceQuestion> {
    let card = session.current()?;
    let id = card.id()?;
    let seed = choice::seed_for(&id, session.choice_seed(), session.appearance(&id));
    if card.multiple_choice {
        // Select-all builds only from the authored option set: AI and sampled
        // distractor pools are shaped for one correct answer.
        let fresh = session.current_fresh(store);
        if session.depth() != Depth::Recognize && !fresh {
            return None;
        }
        return choice::build_authored_multi(card, seed, &card.authored_distractors);
    }
    if session.depth() == Depth::Recognize {
        if !card.authored_distractors.is_empty() {
            return choice::build_authored(card, seed, &card.authored_distractors);
        }
        if let Some(ai) = augment.distractors(&id, card.content_fingerprint)
            && let Some(question) = choice::build(card, seed, ai)
        {
            return Some(question);
        }
        return choice::build_sampled(card, seed, session.cards());
    }
    // `current_fresh`, not a bare store check: a card revealed this sitting
    // is already engaged in the store but keeps its introduction question.
    if session.current_fresh(store) {
        if !card.authored_distractors.is_empty() {
            return choice::build_authored(card, seed, &card.authored_distractors);
        }
        let ai = augment.distractors(&id, card.content_fingerprint);
        return choice::recognition_question(card, seed, ai);
    }
    None
}

pub fn choose(
    session: &Session,
    store: &Store,
    augment: &AugmentCache,
    chosen: usize,
) -> Option<ChoiceFeedback> {
    let question = current_question(session, store, augment)?;
    if question.multiple {
        return None;
    }
    Some(ChoiceFeedback {
        chosen,
        correct: question.correct,
        passed: chosen == question.correct,
    })
}

pub fn choose_multi(
    session: &Session,
    store: &Store,
    augment: &AugmentCache,
    chosen: &[usize],
) -> Option<MultiChoiceFeedback> {
    let question = current_question(session, store, augment)?;
    if !question.multiple {
        return None;
    }
    let mut set: Vec<usize> = chosen.to_vec();
    set.sort_unstable();
    set.dedup();
    if set.iter().any(|&index| index >= question.options.len()) {
        return None;
    }
    let passed = set == question.correct_set;
    Some(MultiChoiceFeedback {
        chosen: set,
        correct: question.correct_set,
        passed,
    })
}

pub fn check_typed(session: &Session, lines: &[String]) -> Option<CheckFeedback> {
    let card = session.current()?;
    let mode = depth::check_for(card.reveal.unwrap_or_default(), session.depth(), card);
    // A quotation is supporting content, not the answer's own prose: typing it
    // back tests transcription rather than understanding.
    let expected: Vec<String> = crate::render::gradeable_answer_lines(card, AnswerSpace::Authored)
        .iter()
        .map(|line| crate::inline::strip_inline_with(line, &card.definitions))
        .collect();
    if expected.is_empty() {
        return Some(CheckFeedback {
            results: Vec::new(),
            passed: false,
        });
    }
    let (results, passed) = if mode == Mode::TypeLine {
        // One field at a time: the reply covers the prefix the learner has
        // actually submitted, so the client can tell progress from completion.
        let attempted = lines.len().min(expected.len());
        let results = answer::grade_lines_ordered(lines, &expected[..attempted]);
        let complete = lines.len() == expected.len();
        let passed = complete && results.iter().all(|r| r.passed);
        (results, passed)
    } else {
        let results = answer::grade_lines_unordered(lines, &expected);
        let passed = results.iter().all(|r| r.passed);
        (results, passed)
    };
    Some(CheckFeedback { results, passed })
}

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

    #[test]
    fn a_reference_link_resolves_against_its_own_decks_definitions() {
        let deck = parser::parse(
            "d.md",
            "## Q\nsee [the ref][r] here\n[r]: https://alix.study\n",
        )
        .unwrap();
        let view = CardView::from(&deck.cards[0]);
        assert!(
            view.back_runs[0]
                .iter()
                .any(|run| run.link && run.text == "the ref"),
            "the card's own table styles its reference: {:?}",
            view.back_runs
        );
        let stray = parser::parse("other.md", "## Q\nsee [the ref][r] here\nanswer\n").unwrap();
        let stray_view = CardView::from(&stray.cards[0]);
        assert!(
            stray_view.back_runs[0].iter().all(|run| !run.link),
            "a deck without the definition keeps the form prose: {:?}",
            stray_view.back_runs
        );
    }
    use crate::{
        answer::Mode,
        augment::AugmentCache,
        card::Card,
        depth::Depth,
        parser,
        scheduler::{Fsrs, Grade},
        session::{Session, SessionOptions},
        store::Store,
    };

    // NOW must stay past T0 + the introduction cooldown, or seen cards won't be
    // servable.
    const T0: u64 = 1_000_000;
    const NOW: u64 = T0 + crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS + 1_000;

    // Stamps each card with a distinct token (cloze sub-cards share their
    // card's token) so store/augment lookups below key on real ids.
    fn parse(text: &str) -> Vec<Card> {
        let mut cards = parser::parse_str("deck.md", text).unwrap();
        let mut n = 0;
        let mut last_line = 0;
        for card in &mut cards {
            if card.line != last_line {
                n += 1;
                last_line = card.line;
            }
            card.token = Some(std::sync::Arc::from(format!("tok{n}").as_str()));
        }
        cards
    }

    fn fixtures() -> (Store, AugmentCache, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path().join("p.json")).unwrap();
        let augment = AugmentCache::open(dir.path().join("a.json"));
        (store, augment, dir)
    }

    #[test]
    fn multiline_projection_keeps_line_breaks_in_text_and_runs() {
        let mut projector = DisplayProjector::default();
        let (text, runs) = project_block("first\nsecond", &mut projector);
        assert_eq!("first\nsecond", text);
        assert_eq!(
            "first\nsecond",
            runs.iter().map(|run| run.text.as_str()).collect::<String>()
        );
    }

    #[test]
    fn only_the_matching_marker_closes_a_projected_code_fence() {
        let lines = ["```", "$x$", "~~~", "$y$", "```", "$z$"]
            .map(str::to_string)
            .to_vec();
        let mut projector = DisplayProjector::default();
        let (_, runs) = project_lines(&lines, &mut projector);
        assert!(runs[..5].iter().flatten().all(|run| run.math.is_none()));
        assert!(runs[5].iter().any(|run| run.math.is_some()));
    }

    #[test]
    fn a_shorter_marker_does_not_close_a_longer_projected_fence() {
        let lines = ["````", "$x$", "```", "$y$", "````", "$z$"]
            .map(str::to_string)
            .to_vec();
        let mut projector = DisplayProjector::default();
        let (_, runs) = project_lines(&lines, &mut projector);
        assert!(runs[..5].iter().flatten().all(|run| run.math.is_none()));
        assert!(runs[5].iter().any(|run| run.math.is_some()));
    }

    /// Spec law 14, the projection half: a section arrives as raw lines plus
    /// inline runs, its fences collapse into one code unit each, and image
    /// syntax inside it stays prose rather than becoming a media element.
    #[test]
    fn a_section_projects_as_prose_runs_and_code_fences_never_as_media() {
        let text = "# *Ownership* and $x$\n\nProse before the card.\n\n```rust\nlet x = 1;\n```\n\n![](assets/diagram.png)\n\n## q\na\n";
        let cards = crate::parser::parse_str("t", text).expect("the fixture parses");
        let card = &cards[0];
        let view = CardView::from(card);

        assert_eq!(
            card.section_context, view.section_context,
            "the raw section lines ride the view untouched"
        );
        assert!(
            view.section_context
                .iter()
                .any(|line| line.contains("assets/diagram.png")),
            "the image line is carried as text: {:?}",
            view.section_context
        );
        assert_eq!(
            view.section_context.len(),
            view.section_context_runs.len(),
            "every section line gets its inline runs"
        );
        assert!(
            view.section_context_runs
                .iter()
                .flatten()
                .any(|run| run.math.is_some()),
            "math in a section heading projects like any other context line"
        );
        assert_eq!(
            1,
            view.section_context_units.len(),
            "the rust fence is one unit: {:?}",
            view.section_context_units
        );
        let ContentUnit::Code { lines } = &view.section_context_units[0] else {
            panic!(
                "a section fence is code, never a diagram: {:?}",
                view.section_context_units
            );
        };
        assert_eq!(vec!["let x = 1;".to_string()], *lines);
        assert!(
            !view
                .section_context_units
                .iter()
                .any(|unit| matches!(unit, ContentUnit::Diagram { .. })),
            "nothing freezes a section fence, so it can never resolve to media"
        );
        assert!(
            view.images.is_empty() && view.images_back.is_empty(),
            "a section image line adds no media element"
        );
    }

    fn session_at(cards: Vec<Card>, store: &mut Store, depth: Depth, now: u64) -> Session {
        Session::new(
            cards,
            store,
            Box::new(Fsrs::default()),
            SessionOptions {
                depth,
                ..Default::default()
            },
            now,
        )
    }

    fn seen(store: &mut Store, cards: &[Card]) {
        for card in cards {
            store
                .get_or_insert(&card.id().unwrap())
                .introduced_ms
                .get_or_insert(T0);
        }
    }

    fn arm(augment: &mut AugmentCache, cards: &[Card]) {
        for card in cards {
            augment.set_distractors(
                &card.id().unwrap(),
                vec!["w1".to_string(), "w2".to_string(), "w3".to_string()],
                card.content_fingerprint,
            );
        }
    }

    #[test]
    fn mode_follows_the_depth_and_reveal_matrix() {
        let (mut store, mut augment, _dir) = fixtures();
        let flip = parse("## q\na\n");
        let line = parse("## q\none\ntwo\n<!-- reveal: line -->\n");
        let many = parse(FOUR);
        seen(&mut store, &flip);
        seen(&mut store, &line);
        seen(&mut store, &many);
        arm(&mut augment, &many);

        let cases = [
            (flip.clone(), Depth::Recall, Mode::Flip),
            (line.clone(), Depth::Recall, Mode::LineByLine),
            (flip.clone(), Depth::Reconstruct, Mode::Typing),
            (line.clone(), Depth::Reconstruct, Mode::TypeLine),
            (many, Depth::Recognize, Mode::Choice),
        ];
        for (cards, depth, want) in cases {
            let session = session_at(cards, &mut store, depth, NOW);
            assert!(session.current().is_some(), "{depth:?} serves the card");
            assert_eq!(
                state(&session, &store, &augment, Some(NOW)).mode,
                want,
                "{depth:?}"
            );
        }
    }

    #[test]
    fn the_next_opening_is_the_decks_earliest_not_this_sittings() {
        let cooldown = crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS;
        let (mut store, augment, _dir) = fixtures();
        let both = parse("## a\n1\n\n## b\n2\n");
        let earlier = both[0].id().unwrap();
        let later = both[1].id().unwrap();
        store.get_or_insert(&earlier).introduced_ms = Some(T0);

        // A sitting one minute on: the earlier card is still cooling, so only
        // the never-met one is rostered, and it cools a minute behind it.
        let now = T0 + 60_000;
        let mut session = session_at(both, &mut store, Depth::Recall, now);
        assert_eq!(
            Some(later),
            session.current().and_then(Card::id),
            "the cooling card stays out of this sitting"
        );
        session.introduce_current(&mut store, now);
        assert!(session.is_finished());

        assert_eq!(
            Some(T0 + cooldown),
            state(&session, &store, &augment, Some(now)).next_due_ms,
            "the summary counts down to the earliest card in the deck"
        );
    }

    #[test]
    fn introducing_flags_a_first_encounter_only() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q\na\n");
        let fresh = session_at(cards.clone(), &mut store, Depth::Recall, NOW);
        assert!(
            state(&fresh, &store, &augment, Some(NOW)).introducing,
            "never-seen card"
        );

        seen(&mut store, &cards);
        let again = session_at(cards, &mut store, Depth::Recall, NOW);
        assert!(
            !state(&again, &store, &augment, Some(NOW)).introducing,
            "seen card"
        );
    }

    #[test]
    fn a_presented_but_unacknowledged_card_keeps_its_introduction_on_ramp() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q\na\n");
        let first = session_at(cards.clone(), &mut store, Depth::Recall, NOW);
        assert!(state(&first, &store, &augment, Some(NOW)).introducing);
        drop(first);

        let again = session_at(cards, &mut store, Depth::Recall, NOW + 1);
        assert!(
            state(&again, &store, &augment, Some(NOW + 1)).introducing,
            "presentation persists nothing, so the reopened card is still introducing"
        );
    }

    #[test]
    fn card_view_carries_context_note_and_images() {
        let (mut store, augment, _dir) = fixtures();
        let mut cards = parse(
            "## q\nthe answer is here\n> [!NOTE]\n> a note line\n<!-- blank: span hidden=\"answer\" b:a1b2c3 -->\n",
        );
        cards[0].images = vec![crate::card::CardImage {
            src: "/pics/front.png".into(),
            alt: None,
            regions: Vec::new(),
            crop: None,
        }];
        cards[0].images_back = vec![crate::card::CardImage {
            src: "/pics/back.png".into(),
            alt: None,
            regions: Vec::new(),
            crop: None,
        }];
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        let card = state(&session, &store, &augment, Some(NOW))
            .card
            .expect("a card");
        assert!(
            card.context.iter().any(|l| l.contains("⍰")),
            "cloze context blanks the hole: {:?}",
            card.context
        );
        assert_eq!(card.back, ["answer"], "the gap text is the answer");
        assert_eq!(
            card.note,
            [NoteView {
                badge: Some(crate::card::Badge::Note),
                units: vec![ContentUnit::Sentence {
                    text: "a note line".into(),
                    runs: crate::inline::parse_inline("a note line"),
                }],
            }]
        );
        assert_eq!(
            card.images
                .iter()
                .map(|i| i.src.as_str())
                .collect::<Vec<_>>(),
            ["/pics/front.png"]
        );
        assert_eq!(
            card.images_back
                .iter()
                .map(|i| i.src.as_str())
                .collect::<Vec<_>>(),
            ["/pics/back.png"]
        );
    }

    /// The end of the path the parser starts: a hole cut from a formula
    /// reaches the client as a rendered math run, not as the characters the
    /// author typed. Without this the learner reveals `\pm` and reads source.
    #[test]
    fn a_revealed_math_span_carries_a_rendered_run() {
        for (label, body, expected_back) in [
            (
                "atom span",
                "$x = a + b$\n<!-- blank: span hidden=\"a\" b:a1b2c3 -->",
                "a",
            ),
            (
                "whole-formula span",
                "$x = a + b$\n<!-- blank: span hidden=\"x = a + b\" b:a1b2c3 -->",
                "x = a + b",
            ),
        ] {
            let source = format!(
                "---\nid: deck-0000000000000000000000000\n---\n# M\n## formula\n{body}\n<!-- id: card-regionregionregionregionre -->\n"
            );
            let deck = crate::parser::parse("m.md", &source)
                .unwrap_or_else(|e| panic!("{label}: deck parses: {e}"));
            let view = CardView::from(&deck.cards[0]);
            assert_eq!(
                view.back,
                [expected_back],
                "{label}: grading content stays plain"
            );
            let run = &view.back_runs[0][0];
            assert_eq!(expected_back, run.text, "{label}: run text stays plain");
            assert!(
                run.math.as_ref().is_some_and(|math| math.svg.is_some()),
                "{label}: a math-classed span must reveal rendered, got {:?}",
                run.math
            );
        }
    }

    #[test]
    fn card_view_projects_math_across_every_card_surface() {
        let mut card = Card::plain(
            std::sync::Arc::from("deck.md"),
            "Find $x^2$".to_string(),
            vec![
                "$$x^2$$".to_string(),
                "```".to_string(),
                "$x^2$".to_string(),
                "```".to_string(),
            ],
            vec![crate::card::Note::bare("Remember $x^2$.".to_string())],
            1,
        );
        card.context = vec!["Use $⍰ + ⬚$".to_string()];

        let view = CardView::from(&card);
        assert_eq!(view.front, "Find x^2");
        assert!(view.front_runs[1].math.is_some());
        assert_eq!(view.context, ["Use $⍰ + ⬚$"]);
        let context_math = view.context_runs[0]
            .iter()
            .find(|run| run.math.is_some())
            .unwrap();
        assert_eq!(context_math.text, "⍰ + ⬚");
        assert!(context_math.math.as_ref().unwrap().svg.is_some());
        assert_eq!(view.back[0], "x^2");
        assert!(view.back_runs[0][0].math.as_ref().unwrap().display);
        assert_eq!(view.back[2], "$x^2$");
        assert!(view.back_runs[2].iter().all(|run| run.math.is_none()));
        let [ContentUnit::Sentence { runs, .. }] = view.note[0].units.as_slice() else {
            panic!("note should remain a sentence");
        };
        assert!(runs.iter().any(|run| run.math.is_some()));
    }

    #[test]
    fn one_card_view_renders_one_copy_of_a_repeated_formula() {
        let mut card = Card::plain(
            std::sync::Arc::from("deck.md"),
            "$x^2$".to_string(),
            vec!["$x^2$".to_string()],
            vec![crate::card::Note::bare("$x^2$".to_string())],
            1,
        );
        card.context = vec!["$x^2$".to_string()];
        let before = crate::math::thread_render_count();
        let view = CardView::from(&card);
        assert_eq!(crate::math::thread_render_count() - before, 1);
        assert!(view.front_runs[0].math.is_some());
    }

    #[test]
    fn card_view_structures_the_note_and_flags_a_reshape() {
        let mut cards =
            parse("## q\nan answer\n> [!NOTE]\n> Intro here.\n> ```\n> let x = 1;\n> ```\n");
        let plain = CardView::from(&cards[0]);
        assert_eq!(
            plain.note,
            [NoteView {
                badge: Some(crate::card::Badge::Note),
                units: vec![
                    ContentUnit::Sentence {
                        text: "Intro here.".into(),
                        runs: crate::inline::parse_inline("Intro here."),
                    },
                    ContentUnit::Code {
                        lines: vec!["let x = 1;".into()]
                    },
                ],
            }],
            "one badged blockquote is one note, and its badge rides the units"
        );
        assert!(!plain.reshaped, "an authored back is not a reshape");
        assert_eq!(plain.back, ["an answer"]);

        cards[0].display_back = Some(vec!["a reshaped answer".into()]);
        let reshaped = CardView::from(&cards[0]);
        assert!(reshaped.reshaped);
        assert_eq!(
            reshaped.back,
            ["a reshaped answer"],
            "back shows the reshape"
        );
    }

    #[test]
    fn an_edited_card_ignores_its_stale_format_reshape() {
        let dir = tempfile::tempdir().unwrap();
        let mut card = parse("## q\nthe authored answer\n").remove(0);
        let id = card.id().unwrap();
        let mut cache = AugmentCache::open(dir.path().join("deck1.json"));
        cache.set_format(
            &id,
            crate::augment::Format {
                back: vec!["a stale reshaped line".into()],
                ..Default::default()
            },
            card.format_fingerprint() ^ 1,
        );

        cache.apply_format(&mut card);
        let stale = CardView::from(&card);
        assert!(!stale.reshaped);
        assert_eq!(["the authored answer"], stale.back.as_slice());

        let mut fresh = card.clone();
        cache.set_format(
            &id,
            crate::augment::Format {
                back: vec!["a fresh reshaped line".into()],
                ..Default::default()
            },
            fresh.format_fingerprint(),
        );
        cache.apply_format(&mut fresh);
        let fresh = CardView::from(&fresh);
        assert!(fresh.reshaped);
        assert_eq!(["a fresh reshaped line"], fresh.back.as_slice());
    }

    #[test]
    fn card_view_carries_all_raw_at_locators_in_authored_order() {
        let cards = parse(
            "## q\n\
             a\n\
             <!-- at: src/lib.rs:10-20 -->\n\
             <!-- at: src/store.rs:30-40 -->\n",
        );
        let view = CardView::from(&cards[0]);
        assert_eq!(view.citations, ["src/lib.rs:10-20", "src/store.rs:30-40"]);
    }

    const FOUR: &str = "## q1\na1\n## q2\na2\n## q3\na3\n## q4\na4\n";

    #[test]
    fn choices_appear_only_at_recognize_or_the_introduction_bar() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(FOUR);
        seen(&mut store, &cards);
        arm(&mut augment, &cards);

        let recall = session_at(cards.clone(), &mut store, Depth::Recall, NOW);
        assert_eq!(state(&recall, &store, &augment, Some(NOW)).choices, None);

        let recognize = session_at(cards.clone(), &mut store, Depth::Recognize, NOW);
        let options = state(&recognize, &store, &augment, Some(NOW))
            .choices
            .expect("cached distractors arm the Recognize pick");
        assert_eq!(options.len(), crate::choice::NUM_OPTIONS);

        let mut fresh_store = Store::open(_dir.path().join("fresh.json")).unwrap();
        let empty_augment = AugmentCache::open(_dir.path().join("empty.json"));
        let introduction = session_at(cards.clone(), &mut fresh_store, Depth::Recall, NOW);
        let bare = state(&introduction, &fresh_store, &empty_augment, Some(NOW));
        assert!(bare.introducing);
        assert_eq!(bare.choices, None, "no distractors, no introduction pick");

        let armed = state(&introduction, &fresh_store, &augment, Some(NOW));
        assert!(armed.choices.is_some(), "full distractors arm the pick");
    }

    #[test]
    fn a_recognize_card_with_no_buildable_pick_falls_back_to_flip() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## lone q\nlone a\n");
        seen(&mut store, &cards);
        let recognize = session_at(cards, &mut store, Depth::Recognize, NOW);
        let s = state(&recognize, &store, &augment, Some(NOW));
        assert_eq!(s.choices, None, "no siblings, no pick");
        assert_eq!(s.mode, Mode::Flip, "a choiceless Recognize card is a flip");
    }

    const TABLE_DECK: &str = "| w | m |\n|---|---|\n| a | alpha | <!-- r:aaaaaa -->\n| b | beta | <!-- r:bbbbbb -->\n| c | gamma | <!-- r:cccccc -->\n| d | delta | <!-- r:dddddd -->\n<!-- cards -->\n<!-- id: card-9w2c7x4k1m8q3z5t0v6b2n4d8f -->\n";

    #[test]
    fn a_table_card_samples_its_column_without_any_authored_or_cached_source() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parser::parse_str("deck.md", TABLE_DECK).unwrap();
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let question = current_question(&session, &store, &augment).expect("a sampled pick");
        assert_eq!(4, question.options.len());
        let column = ["alpha", "beta", "gamma", "delta"];
        assert!(
            question
                .options
                .iter()
                .all(|option| column.contains(&option.as_str())),
            "every option comes from the meaning column: {:?}",
            question.options
        );
        let distinct: std::collections::HashSet<&str> =
            question.options.iter().map(String::as_str).collect();
        assert_eq!(4, distinct.len(), "four distinct column values");
    }

    #[test]
    fn a_cached_ai_source_outranks_column_sampling() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parser::parse_str("deck.md", TABLE_DECK).unwrap();
        seen(&mut store, &cards);
        arm(&mut augment, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let question = current_question(&session, &store, &augment).expect("an AI pick");
        for (index, option) in question.options.iter().enumerate() {
            if index != question.correct {
                assert!(
                    option.starts_with('w'),
                    "a cached distractor, not a column value: {option:?}"
                );
            }
        }
    }

    #[test]
    fn an_unbuildable_ai_cache_falls_back_to_table_column_sampling() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parser::parse_str("deck.md", TABLE_DECK).unwrap();
        seen(&mut store, &cards);
        for card in &cards {
            augment.set_distractors(
                &card.id().unwrap(),
                vec!["only one usable distractor".into()],
                card.content_fingerprint,
            );
        }
        assert!(crate::depth::deck_recognizable(&cards, &augment));
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);

        let question = current_question(&session, &store, &augment)
            .expect("the buildable table column must backstop an incomplete AI cache");

        assert_eq!(4, question.options.len());
    }

    #[test]
    fn authored_distractors_replace_ai_choices_at_recognize() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(
            "## capital\n- [x] Paris\n- [ ] London\n- [ ] Berlin\n<!-- choices: single -->\n",
        );
        seen(&mut store, &cards);
        arm(&mut augment, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let question = current_question(&session, &store, &augment).expect("an authored pick");
        assert_eq!(3, question.options.len());
        assert_eq!("Paris", question.options[question.correct]);
        assert!(
            question
                .options
                .iter()
                .all(|option| !option.starts_with('w'))
        );
    }

    #[test]
    fn a_cooled_card_coming_back_cannot_regrade_the_pick_shown_for_another() {
        use crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS;
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(
            "## bottom layer\nUnit\n## middle layer\nintegration\n## top layer\nend-to-end\n",
        );
        seen(&mut store, &cards);
        for (card, distractors) in cards.iter().zip([
            ["Acceptance", "Smoke", "Manual"],
            ["component", "contract", "system"],
            ["load", "regression", "exploratory"],
        ]) {
            augment.set_distractors(
                &card.id().unwrap(),
                distractors.iter().map(|d| d.to_string()).collect(),
                card.content_fingerprint,
            );
        }
        // After the introduction cooldown from `seen`'s T0, so the met cards are due.
        let now = T0 + DEFAULT_INTRODUCTION_COOLDOWN_MS + 60_000;
        let mut session = session_at(cards, &mut store, Depth::Recognize, now);

        // Miss the first hole, which floors it and moves the learner to the next.
        session.grade(&mut store, crate::scheduler::Grade::Fail, now);
        let shown = current_question(&session, &store, &augment).expect("a pick");
        let displayed = shown.options.clone();
        let picked = shown.correct;

        // The floored hole comes back off cooldown. Reading state must not swap
        // the card underneath the learner: the client still shows `displayed`
        // and gets only an index back, so a swap regrades one card's pick
        // against another card's answer key.
        let shown_card = session.current().and_then(|c| c.id());
        session.poll(&mut store, now + DEFAULT_INTRODUCTION_COOLDOWN_MS);

        // Asserting on `passed` alone is not enough: two questions can put the
        // answer at the same index, hiding the swap behind a coincidence.
        assert_eq!(
            shown_card,
            session.current().and_then(|c| c.id()),
            "the card being graded must be the card the learner was shown"
        );
        let feedback = choose(&session, &store, &augment, picked).expect("feedback");
        assert!(
            feedback.passed,
            "learner saw {displayed:?} and picked {picked}, server flagged {} correct",
            feedback.correct
        );
    }

    #[test]
    fn every_card_marks_its_own_authored_answer_correct() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(
            "## bottom layer\nUnit\n## middle layer\nintegration\n## top layer\nend-to-end\n",
        );
        seen(&mut store, &cards);
        // Cached sets copied from a real deck, per card.
        let per_hole = [
            ("Unit", ["Acceptance", "Smoke", "Manual"]),
            ("integration", ["component", "contract", "system"]),
            ("end-to-end", ["load", "regression", "exploratory"]),
        ];
        for (card, (_, distractors)) in cards.iter().zip(per_hole.iter()) {
            augment.set_distractors(
                &card.id().unwrap(),
                distractors.iter().map(|d| d.to_string()).collect(),
                card.content_fingerprint,
            );
        }
        assert_eq!(3, cards.len(), "three cards");

        for (index, (answer, _)) in per_hole.iter().enumerate() {
            let session = session_at(
                vec![cards[index].clone()],
                &mut store,
                Depth::Recognize,
                NOW,
            );
            let q = current_question(&session, &store, &augment).expect("a pick");
            assert_eq!(
                *answer, q.options[q.correct],
                "hole {index}: options {:?} flagged {} correct",
                q.options, q.correct
            );
        }
    }

    #[test]
    fn the_displayed_answer_still_passes_after_the_session_is_polled() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(
            "## capital\n- [x] Paris\n- [ ] London\n- [ ] Berlin\n<!-- choices: single -->\n",
        );
        seen(&mut store, &cards);
        let mut session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let shown = current_question(&session, &store, &augment).expect("a pick");
        // The learner clicks the option the client is displaying as the answer.
        let picked = shown.correct;

        // Reading session state must not reshuffle the question underneath the
        // learner: the client keeps the options it already rendered and only
        // receives an index back.
        session.poll(&mut store, NOW + 1);

        let feedback = choose(&session, &store, &augment, picked).expect("feedback");
        assert!(
            feedback.passed,
            "picking the displayed answer must pass; options were {:?}, server now says {} is correct",
            shown.options, feedback.correct
        );
    }

    #[test]
    fn authored_choices_vary_between_study_sessions() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(
            "## capital\n- [x] Paris\n- [ ] London\n- [ ] Berlin\n<!-- choices: single -->\n",
        );
        seen(&mut store, &cards);
        let first = current_question(
            &session_at(cards.clone(), &mut store, Depth::Recognize, NOW),
            &store,
            &augment,
        )
        .expect("an authored pick")
        .options;

        let later_session_varies = (1..12).any(|offset| {
            current_question(
                &session_at(cards.clone(), &mut store, Depth::Recognize, NOW + offset),
                &store,
                &augment,
            )
            .expect("an authored pick")
            .options
                != first
        });
        assert!(
            later_session_varies,
            "a fresh study session must not repeat a memorized option order"
        );
    }

    #[test]
    fn authored_distractors_drive_the_never_seen_introduction_attempt() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(
            "## capital\n- [x] Paris\n- [ ] London\n- [ ] Berlin\n<!-- choices: single -->\n",
        );
        // AI distractors exist in the cache but must be ignored for an authored card.
        arm(&mut augment, &cards);
        // Never seen (no `seen(...)`) and depth is Recall, not Recognize: this is the
        // first-meeting introduction attempt, which must still use the authored options.
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        let question = current_question(&session, &store, &augment)
            .expect("introduction MC from authored options");
        assert_eq!(
            3,
            question.options.len(),
            "authored options, not padded to the AI four"
        );
        assert_eq!("Paris", question.options[question.correct]);
    }

    #[test]
    fn state_options_and_choose_agree_and_hold_still() {
        let (mut store, mut augment, _dir) = fixtures();
        let cards = parse(FOUR);
        seen(&mut store, &cards);
        arm(&mut augment, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);

        let question = current_question(&session, &store, &augment).expect("a pick");
        let served = state(&session, &store, &augment, Some(NOW));
        let shown = served.choices.as_ref().expect("options");
        assert_eq!(shown, &question.options, "state serves the same options");
        assert_eq!(
            served.choice_runs.as_ref().map(Vec::len),
            Some(question.options.len())
        );
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).choices,
            Some(question.options.clone())
        );

        let right = choose(&session, &store, &augment, question.correct).expect("feedback");
        assert!(right.passed);
        assert_eq!(right.correct, question.correct);
        let wrong_index = (question.correct + 1) % question.options.len();
        let wrong = choose(&session, &store, &augment, wrong_index).expect("feedback");
        assert!(!wrong.passed);
        assert_eq!(wrong.correct, question.correct, "feedback names the answer");
    }

    #[test]
    fn check_typed_fails_a_grouped_card_answered_only_in_part() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse(
            "## carpals\nThe scaphoid and the lunate.\n<!-- blank: span [w] hidden=\"scaphoid\" b:a1b2c3 -->\n<!-- blank: span [w] hidden=\"lunate\" b:d4e5f6 -->\n",
        );
        assert_eq!(1, cards.len(), "one grouped card");
        assert_eq!(2, cards[0].back.len(), "asking two spans");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);
        let feedback = check_typed(&session, &["scaphoid".to_string()]).expect("feedback");
        assert!(
            !feedback.passed,
            "one submitted line cannot pass a two-span card"
        );
    }

    #[test]
    fn a_quotation_is_not_part_of_the_typed_target() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## q\nthe answer's own prose\n> a quoted passage\n> its second line\n");
        assert_eq!(
            3,
            cards[0].back.len(),
            "the quote is answer content and stays in back: {:?}",
            cards[0].back
        );
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback =
            check_typed(&session, &["the answer's own prose".to_string()]).expect("feedback");
        assert!(
            feedback.passed,
            "typing the answer's prose passes without transcribing the quotation: {:?}",
            feedback.results
        );
        assert_eq!(
            1,
            feedback.results.len(),
            "one gradeable line, not three: {:?}",
            feedback.results
        );
    }

    #[test]
    fn a_blank_submission_never_proves_reconstruction_of_a_quote_only_answer() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## q\n> the whole answer is a quotation\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &[String::new()]).expect("feedback");
        assert!(
            !feedback.passed,
            "a blank submission must not prove reconstruction: {:?}",
            feedback.results
        );
    }

    #[test]
    fn a_leading_quotation_does_not_shift_the_typed_fields() {
        let (mut store, _augment, _dir) = fixtures();
        let cards =
            parse("## q\n> a quoted passage\nthe answer's own prose\n<!-- reveal: line -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback =
            check_typed(&session, &["the answer's own prose".to_string()]).expect("feedback");
        assert!(
            feedback.passed,
            "the one gradeable line is asked in the one field: {:?}",
            feedback.results
        );
        assert_eq!(
            1,
            feedback.results.len(),
            "a quotation owns no typed field, so it owes no result"
        );

        let padded = vec![String::new(), "the answer's own prose".to_string()];
        let feedback = check_typed(&session, &padded).expect("feedback");
        assert!(
            !feedback.passed,
            "a field for the quotation is one field too many, not a blank to skip: {:?}",
            feedback.results
        );
    }

    #[test]
    fn a_blank_answer_that_is_a_greater_than_sign_is_exact_text_not_a_quote() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse(
            "## comparison\nleft > right\n<!-- blank: span hidden=\">\" boundary=char b:a1b2c3 -->\n",
        );
        assert!(cards[0].is_blank_card(), "the parser produced a blank card");
        assert_eq!([">"], cards[0].back.as_slice());
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &[">".to_string()]).expect("feedback");
        assert!(
            feedback.passed,
            "the literal hidden span must remain gradeable: {:?}",
            feedback.results
        );
    }

    /// Under `reveal: line` the client sends one field per gradeable line, so
    /// a quotation anywhere in the answer must neither claim a field nor shift
    /// which expected line the next field is graded against.
    #[test]
    fn a_quotation_owns_no_typed_field_wherever_it_sits() {
        let rows: Vec<(&str, &str)> = vec![
            ("> quoted\nalpha\nbeta", "a quotation first"),
            (
                "alpha\n> quoted\nbeta",
                "a quotation between the gradeable lines",
            ),
            ("alpha\nbeta\n> quoted", "a quotation last"),
            (
                "alpha\n> quoted\n> still quoted\nbeta",
                "a two-line quotation is one block and still no field",
            ),
        ];
        for (back, why) in rows {
            let (mut store, _augment, _dir) = fixtures();
            let cards = parse(&format!("## q\n{back}\n<!-- reveal: line -->\n"));
            seen(&mut store, &cards);
            let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

            let feedback = check_typed(&session, &["alpha".to_string(), "beta".to_string()])
                .expect("feedback");
            assert!(feedback.passed, "{why}: {:?}", feedback.results);
            assert_eq!(
                2,
                feedback.results.len(),
                "{why}: one result per gradeable line"
            );

            let swapped = check_typed(&session, &["beta".to_string(), "alpha".to_string()])
                .expect("feedback");
            assert!(
                !swapped.passed,
                "{why}: the fields are ordered, so a swap must not pass: {:?}",
                swapped.results
            );
        }
    }

    #[test]
    fn a_typeline_check_returns_only_the_prefix_the_learner_has_attempted() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## q\none\ntwo\n<!-- reveal: line -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &["one".to_string()]).expect("feedback");
        assert_eq!(
            1,
            feedback.results.len(),
            "the client decides from the result count whether another field is owed: {:?}",
            feedback.results
        );
        assert!(!feedback.passed, "one line cannot finish a two-line answer");
    }

    #[test]
    fn a_typeline_surplus_input_is_a_failed_result_not_a_silent_pass() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## q\none\ntwo\n<!-- reveal: line -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(
            &session,
            &["one".to_string(), "two".to_string(), "surplus".to_string()],
        )
        .expect("feedback");
        assert!(
            !feedback.passed,
            "surplus input was silently accepted as a correct complete answer: {:?}",
            feedback.results
        );
        assert_eq!(3, feedback.results.len(), "one result per line sent");
        assert_eq!("", feedback.results[2].expected);
        assert!(!feedback.results[2].passed);

        // A BLANK surplus line grades as passing on its own (nothing against
        // nothing), so completeness has to be measured on what was sent, not
        // on the prefix the answer could absorb.
        let blank_surplus = check_typed(
            &session,
            &["one".to_string(), "two".to_string(), String::new()],
        )
        .expect("feedback");
        assert!(
            blank_surplus.results.iter().all(|r| r.passed),
            "every result passes on its own: {:?}",
            blank_surplus.results
        );
        assert!(
            !blank_surplus.passed,
            "and the card still does not complete, because a field too many is \
             a client out of step: {:?}",
            blank_surplus.results
        );
    }

    /// One card, one answer space. A typed mode grades exact words, so every
    /// answer-bearing field it is served must be the deck's own: serving the
    /// reshape while grading the authored answer is the split that let an
    /// unvalidated relabel become the target.
    #[test]
    fn a_typed_mode_is_served_the_authored_answer_and_a_reveal_mode_the_reshape() {
        let (mut store, augment, _dir) = fixtures();
        let rows = [
            (
                "",
                Depth::Reconstruct,
                Mode::Typing,
                "PCIe generation",
                false,
            ),
            (
                "<!-- reveal: line -->\n",
                Depth::Reconstruct,
                Mode::TypeLine,
                "PCIe generation",
                false,
            ),
            ("", Depth::Recall, Mode::Flip, "Bus generation: PCIe", true),
            (
                "<!-- reveal: line -->\n",
                Depth::Recall,
                Mode::LineByLine,
                "Bus generation: PCIe",
                true,
            ),
        ];
        for (directive, depth, expected_mode, expected_back, expected_reshaped) in rows {
            let mut cards = parse(&format!(
                "## What does the number after PCIe mean?\nPCIe generation\n{directive}"
            ));
            cards[0].display_back = Some(vec!["Bus generation: PCIe".into()]);
            seen(&mut store, &cards);
            let session = session_at(cards, &mut store, depth, NOW);

            let served = state(&session, &store, &augment, Some(NOW));
            assert_eq!(expected_mode, served.mode, "{expected_mode:?}");
            let card = served.card.expect("a card is served");
            assert_eq!(
                [expected_back],
                card.back.as_slice(),
                "{expected_mode:?}: back"
            );
            assert_eq!(
                expected_reshaped, card.reshaped,
                "{expected_mode:?}: reshaped must describe what was actually served"
            );
            assert_eq!(
                1,
                card.answer_steps.len(),
                "{expected_mode:?}: one line, one step"
            );
        }
    }

    #[test]
    fn a_format_reshape_does_not_change_exact_authored_grading() {
        let (mut store, _augment, _dir) = fixtures();
        let mut cards = parse("## What does the number after PCIe mean?\nPCIe generation\n");
        cards[0].display_back = Some(vec!["Bus generation: PCIe".into()]);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &["PCIe generation".to_string()]).expect("feedback");
        assert!(
            feedback.passed,
            "the deck's authored answer must stay the exact target: {:?}",
            feedback.results
        );
    }

    #[test]
    fn a_reshaped_typeline_grades_the_authored_answer_it_is_served() {
        let (mut store, _augment, _dir) = fixtures();
        let mut cards = parse("## q\nA, B, C\n<!-- reveal: line -->\n");
        cards[0].display_back = Some(vec!["A".into(), "B".into(), "C".into()]);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &["A, B, C".to_string()]).expect("feedback");
        assert!(
            feedback.passed,
            "the deck's own words are the target: {:?}",
            feedback.results
        );

        let displayed = check_typed(
            &session,
            &["A".to_string(), "B".to_string(), "C".to_string()],
        )
        .expect("feedback");
        assert!(
            !displayed.passed,
            "the reshape's three display lines are not three fields to type: {:?}",
            displayed.results
        );
    }

    #[test]
    fn a_quote_marker_inside_a_fence_is_still_typed_content() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## q\n```text\n> not a quotation\n```\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);

        let feedback = check_typed(&session, &["```text".to_string()]).expect("feedback");
        assert_eq!(
            3,
            feedback.results.len(),
            "a fence's interior is source, so its `>` line is graded: {:?}",
            feedback.results
        );
    }

    #[test]
    fn check_typed_orders_only_for_typeline() {
        let (mut store, _augment, _dir) = fixtures();
        let line = parse("## q\none\ntwo\n<!-- reveal: line -->\n");
        seen(&mut store, &line);
        let typeline = session_at(line, &mut store, Depth::Reconstruct, NOW);
        let swapped = vec!["two".to_string(), "one".to_string()];
        let ordered = check_typed(&typeline, &swapped).expect("feedback");
        assert!(!ordered.passed, "typeline is position-sensitive");

        let multi = parse("## q\none\ntwo\n");
        seen(&mut store, &multi);
        let unordered_session = session_at(multi, &mut store, Depth::Reconstruct, NOW);
        let unordered = check_typed(&unordered_session, &swapped).expect("feedback");
        assert!(unordered.passed, "any order matches the same lines");
        assert_eq!(unordered.results.len(), 2);
    }

    #[test]
    fn typed_grading_accepts_plain_content_for_a_formatted_answer() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## capital\n**Paris**\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);
        let feedback = check_typed(&session, &["Paris".to_string()]).expect("feedback");
        assert!(feedback.passed);
        assert_eq!("Paris", feedback.results[0].expected);
    }

    #[test]
    fn typed_grading_accepts_latex_source_without_math_delimiters() {
        let (mut store, _augment, _dir) = fixtures();
        let cards = parse("## square\n$x^2$\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);
        let feedback = check_typed(&session, &["x^2".to_string()]).expect("feedback");
        assert!(feedback.passed);
        assert_eq!("x^2", feedback.results[0].expected);
    }

    #[test]
    fn blank_grading_uses_the_styled_spans_plain_content() {
        let (mut store, _augment, _dir) = fixtures();
        let cards =
            parse("## capital\n**Paris**\n<!-- blank: span hidden=\"Paris\" b:a1b2c3 -->\n");
        assert_eq!(["Paris"], cards[0].back.as_slice());
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);
        let feedback = check_typed(&session, &["Paris".to_string()]).expect("feedback");
        assert!(feedback.passed);
        assert_eq!("Paris", feedback.results[0].expected);
    }

    #[test]
    fn keypoints_appear_only_for_an_explain_check_past_introduction() {
        let (mut store, mut augment, _dir) = fixtures();
        let mut cards = parse("## q\nfirst fact\nsecond fact\n");
        seen(&mut store, &cards);

        cards[0].display_back = Some(vec!["a reshaped".into(), "answer".into()]);
        let session = session_at(cards.clone(), &mut store, Depth::Reconstruct, NOW);
        let fallback = state(&session, &store, &augment, Some(NOW));
        assert_eq!(fallback.mode, Mode::Explain);
        assert_eq!(
            fallback.keypoints,
            Some(vec!["first fact".to_string(), "second fact".to_string()])
        );
        assert_eq!(fallback.keypoint_runs.as_ref().map(Vec::len), Some(2));

        augment.set_keypoints(
            &cards[0].id().unwrap(),
            vec!["one claim".to_string()],
            cards[0].content_fingerprint,
        );
        let cached = state(&session, &store, &augment, Some(NOW));
        assert_eq!(cached.keypoints, Some(vec!["one claim".to_string()]));
        assert_eq!(cached.keypoint_runs.as_ref().map(Vec::len), Some(1));

        let recall = session_at(cards.clone(), &mut store, Depth::Recall, NOW);
        assert_eq!(state(&recall, &store, &augment, Some(NOW)).keypoints, None);

        let mut fresh = Store::open(_dir.path().join("fresh.json")).unwrap();
        let introduction = session_at(cards, &mut fresh, Depth::Reconstruct, NOW);
        let introduced = state(&introduction, &fresh, &augment, Some(NOW));
        assert!(introduced.introducing);
        assert_eq!(introduced.keypoints, None);
    }

    #[test]
    fn explain_fallback_keypoints_exclude_supporting_quotations() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(
            "## q\nfirst claim\nsecond claim\n> supporting quotation\n> continued quotation\n",
        );
        seen(&mut store, &cards);

        let session = session_at(cards, &mut store, Depth::Reconstruct, NOW);
        let fallback = state(&session, &store, &augment, Some(NOW));

        assert_eq!(fallback.mode, Mode::Explain);
        assert_eq!(
            fallback.keypoints,
            Some(vec!["first claim".to_string(), "second claim".to_string()]),
            "the checklist grades the answer's claims, not its supporting quotation"
        );
    }

    #[test]
    fn session_counters_mirror_the_session() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(FOUR);
        seen(&mut store, &cards);
        let mut session = session_at(cards, &mut store, Depth::Recall, NOW);
        let start = state(&session, &store, &augment, Some(NOW));
        assert_eq!(start.initial, 4);
        assert_eq!((start.reviews, start.passed, start.failed), (0, 0, 0));

        session.grade(&mut store, Grade::Pass, NOW);
        session.grade(&mut store, Grade::Fail, NOW);
        let later = state(&session, &store, &augment, Some(NOW));
        assert_eq!(later.reviews, 2);
        assert_eq!(later.passed, 1);
        assert_eq!(later.failed, 1);
    }

    #[test]
    fn an_introduction_only_sitting_reports_its_introduced_count() {
        let (_store, augment, _dir) = fixtures();
        let cards = parse(FOUR);
        let mut fresh = Store::open(_dir.path().join("fresh.json")).unwrap();
        let mut session = session_at(cards, &mut fresh, Depth::Recall, NOW);
        session.introduce_current(&mut fresh, NOW);
        session.introduce_current(&mut fresh, NOW);
        let s = state(&session, &fresh, &augment, Some(NOW));
        assert_eq!(s.introduced, 2, "the summary must know new cards were met");
        assert_eq!((s.reviews, s.passed, s.failed), (0, 0, 0));
    }

    #[test]
    fn an_empty_finished_session_reports_the_soonest_next_due() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q1\na1\n## q2\na2\n");
        let sooner = cards[0].id().unwrap();
        let later = cards[1].id().unwrap();
        // Both cards met and still cooling: `sooner` comes due before `later`.
        store.get_or_insert(&sooner).introduced_ms = Some(NOW);
        store.get_or_insert(&later).introduced_ms = Some(NOW + 10_000);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert!(
            session.is_finished(),
            "every card is still inside its introduction cooldown"
        );
        let s = state(&session, &store, &augment, Some(NOW));
        let cooldown = crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS;
        assert_eq!(
            s.next_due_ms,
            Some(NOW + cooldown),
            "the soonest due instant (the sooner card), not the latest"
        );
    }

    #[test]
    fn an_empty_finished_session_with_nothing_scheduled_has_no_next_due() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q1\na1\n");
        // No card has stored state and new intake is off, so the roster is
        // empty and there is nothing to be due.
        let session = Session::new(
            cards,
            &mut store,
            Box::new(Fsrs::default()),
            SessionOptions {
                new_cards_percent: 0,
                max_session: 0,
                ..Default::default()
            },
            NOW,
        );
        assert!(session.is_finished());
        let s = state(&session, &store, &augment, Some(NOW));
        assert_eq!(s.next_due_ms, None);
    }

    #[test]
    fn a_due_instant_equal_to_now_is_not_a_future_wakeup() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q1\na1\n");
        let id = cards[0].id().unwrap();
        store.get_or_insert(&id).introduced_ms = Some(T0);
        let now = T0 + crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS;
        let session = Session::new(
            cards,
            &mut store,
            Box::new(Fsrs::default()),
            SessionOptions {
                max_session: 0,
                new_cards_percent: 0,
                ..Default::default()
            },
            now,
        );
        assert!(session.is_finished());

        assert_eq!(
            None,
            state(&session, &store, &augment, Some(now)).next_due_ms,
            "an opening at the present instant is due now, not a future countdown"
        );
    }

    #[test]
    fn an_active_session_carries_no_next_due() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(FOUR);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert!(!session.is_finished());
        let s = state(&session, &store, &augment, Some(NOW));
        assert_eq!(s.next_due_ms, None, "only the finished payload carries it");
    }

    #[test]
    fn a_sitting_that_only_introduced_reports_when_those_cards_return() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(FOUR);
        let card_count = cards.len();
        let mut session = session_at(cards, &mut store, Depth::Recall, NOW);
        for index in 0..card_count {
            assert!(
                !session.is_finished(),
                "session finished after only {index} of {card_count} introductions"
            );
            session.introduce_current(&mut store, NOW);
        }
        assert!(
            session.is_finished(),
            "session did not finish after introducing all {card_count} cards once"
        );
        let s = state(&session, &store, &augment, Some(NOW));

        assert!(s.introduced > 0, "the sitting introduced cards");
        assert_eq!(0, s.reviews, "and graded none");
        assert_eq!(
            Some(NOW + crate::scheduler::DEFAULT_INTRODUCTION_COOLDOWN_MS),
            s.next_due_ms,
            "the client cannot say when they come back without this"
        );
    }

    #[test]
    fn can_restart_flips_with_the_injected_clock() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q\na\n");
        seen(&mut store, &cards);
        let mut session = session_at(cards, &mut store, Depth::Recall, NOW);
        session.grade(&mut store, Grade::Pass, NOW);
        assert!(session.is_finished());

        let done = state(&session, &store, &augment, Some(NOW));
        assert!(!done.can_restart, "nothing is due right after the pass");
        let much_later = NOW + 90 * 24 * 3_600_000;
        let again = state(&session, &store, &augment, Some(much_later));
        assert!(again.can_restart, "the card comes due again");
    }

    #[test]
    fn input_follows_the_card() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse("## q\na\n<!-- input: draw -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).input,
            Input::Draw
        );
    }

    #[test]
    fn explicit_draw_input_reaches_a_math_span_review_card() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(
            "## q\n---\n$\\gamma$\n<!-- input: draw -->\n<!-- blank: span hidden=\"\\\\gamma\" b:a1b2c3 -->\n",
        );
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).input,
            Input::Draw,
            "the authored span input must reach the review client"
        );
    }

    #[test]
    fn an_unpinned_math_span_draws_by_default() {
        let (mut store, augment, _dir) = fixtures();
        let cards =
            parse("## q\n---\n$\\gamma$\n<!-- blank: span hidden=\"\\\\gamma\" b:a1b2c3 -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).input,
            Input::Draw,
            "the formula rule: a math span sketches unless pinned"
        );
    }

    #[test]
    fn a_block_input_pin_reaches_a_prose_span_card() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(
            "## q\nthe value is dropped\n<!-- input: draw -->\n<!-- blank: span hidden=\"dropped\" b:a1b2c3 -->\n",
        );
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).input,
            Input::Draw,
            "the block directive routes to the span card"
        );
    }

    #[test]
    fn a_span_cut_from_prose_is_typed_by_default() {
        let (mut store, augment, _dir) = fixtures();
        let cards =
            parse("## q\nthe value is dropped\n<!-- blank: span hidden=\"dropped\" b:a1b2c3 -->\n");
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recall, NOW);
        assert_eq!(
            state(&session, &store, &augment, Some(NOW)).input,
            Input::Type
        );
    }

    /// The rule fills a gap and never overrules. A deck-level `input:` lands
    /// on the card before this point (deck.rs), so pinning it on the card
    /// covers both ways an author can say it.

    #[test]
    fn a_finished_session_reports_no_card_and_no_choices() {
        let (mut store, augment, _dir) = fixtures();
        let session = session_at(Vec::new(), &mut store, Depth::Recall, NOW);
        let state = state(&session, &store, &augment, Some(NOW));
        assert!(state.finished);
        assert!(state.card.is_none());
        assert_eq!(state.choices, None);
        assert!(!state.introducing);
        assert_eq!(state.remaining, 0);
        assert_eq!(check_typed(&session, &["x".to_string()]), None);
        assert_eq!(choose(&session, &store, &augment, 0), None);
    }

    #[test]
    fn a_region_cards_view_classifies_asked_sibling_and_cover_masks() {
        let text = "## bones\n![](hand.png)\n                    <!-- blank: rect x=10 y=20 width=30 height=40 hidden=\"lunate\" b:a1b2c3 -->\n                    <!-- blank: rect x=50 y=60 width=30 height=40 hidden=\"hamate\" b:d4e5f6 -->\n                    <!-- cover: rect x=1 y=2 width=3 height=4 -->\n                    <!-- crop: rect x=0 y=0 width=90 height=90 -->\n\n---\nthe carpals\n<!-- id: card-bonesbonesbonesbonesbones -->\n";
        let cards = crate::parser::parse_str("t.md", text).unwrap();
        let lunate_card = cards
            .iter()
            .find(|card| card.back == vec!["lunate".to_string()])
            .expect("the first blank produced a card");
        let view = CardView::from(lunate_card);
        let image = &view.images[0];

        let roles: Vec<RegionRole> = image.regions.iter().map(|r| r.role).collect();
        assert_eq!(
            vec![RegionRole::Asked, RegionRole::Mask, RegionRole::Cover],
            roles,
            "own blank asked, the sibling's masked, the cover covered"
        );
        let reveals: Vec<bool> = image.regions.iter().map(|r| r.reveal_on_answer).collect();
        assert_eq!(
            vec![true, false, false],
            reveals,
            "on a region card only the asked blank reveals; the cover protects siblings"
        );
        assert_eq!(10.0, image.regions[0].x);
        assert_eq!(40.0, image.regions[0].height);
        assert_eq!("px", image.regions[0].unit);
        let crop = image.crop.as_ref().expect("the crop rides the view");
        assert_eq!(90.0, crop.width);

        assert!(
            cards.iter().all(|card| card.region.is_some()),
            "a blank-bearing block is a template: no plain card exists"
        );
        let hamate_card = cards
            .iter()
            .find(|card| card.back == vec!["hamate".to_string()])
            .expect("the second blank produced a card");
        let sibling_roles: Vec<RegionRole> = CardView::from(hamate_card).images[0]
            .regions
            .iter()
            .map(|r| r.role)
            .collect();
        assert_eq!(
            vec![RegionRole::Mask, RegionRole::Asked, RegionRole::Cover],
            sibling_roles,
            "each region card asks its own blank and masks the sibling's"
        );
    }

    fn masked_fence_deck() -> Vec<crate::card::Card> {
        let text = concat!(
            "## the request path\n",
            "```mermaid\n",
            "flowchart LR\n",
            "  Cache[store] --> B[Cache]\n",
            "```\n",
            "<!-- blank: span hidden=\"store\" -->\n",
            "<!-- blank: span hidden=\"Cache\" occurrence=2 -->\n",
        );
        crate::parser::parse_str("t.md", text).unwrap()
    }

    fn masked_fence_geometry(
        extra: Vec<crate::diagram::GeometryLabel>,
    ) -> crate::card::ResolvedDiagram {
        let interior = "flowchart LR\n  Cache[store] --> B[Cache]";
        let store = interior.find("store").unwrap() as u32;
        let cache = interior.rfind("Cache").unwrap() as u32;
        let label =
            |id: &str, text: &str, start: u32, end: u32, y: u32| crate::diagram::GeometryLabel {
                id: id.into(),
                text: text.into(),
                source: crate::diagram::LabelSource::Range { start, end },
                bounds: crate::diagram::PixelBox {
                    x: 10,
                    y,
                    width: 100,
                    height: 40,
                },
            };
        let mut labels = vec![
            label("Cache", "store", store, store + 5, 10),
            label("B", "Cache", cache, cache + 5, 50),
        ];
        labels.extend(extra);
        crate::card::ResolvedDiagram {
            fingerprint: crate::diagram::fingerprint(interior),
            png: std::path::PathBuf::from("/ws/assets/deck-x/sha256-aa.png"),
            geometry: crate::diagram::DiagramGeometry {
                image: "sha256-aa.png".to_string(),
                image_width: 376,
                image_height: 228,
                logical_width: 188,
                logical_height: 114,
                labels,
            },
        }
    }

    #[test]
    fn a_bound_span_projects_regions_and_a_leak_free_label_inventory() {
        let mut cards = masked_fence_deck();
        assert_eq!(2, cards.len(), "two blanks make two region cards");
        let card = cards
            .iter_mut()
            .find(|card| card.back == ["Cache"])
            .expect("the card asking the Cache label");
        card.resolved_diagrams = vec![masked_fence_geometry(Vec::new())];
        let view = CardView::from(&*card);
        let ContentUnit::Diagram {
            regions,
            alt,
            revealed_alt,
            ..
        } = &view.context_units[0]
        else {
            panic!("the fence projects as a diagram: {:?}", view.context_units);
        };
        assert_eq!(2, regions.len(), "asked plus sibling: {regions:?}");
        let asked = regions
            .iter()
            .find(|region| region.role == RegionRole::Asked)
            .expect("the asked region");
        assert!(asked.reveal_on_answer, "the asked mask lifts on answer");
        assert_eq!(
            (50.0, 100.0),
            (asked.y, asked.width),
            "the asked box is the Cache label's raster box"
        );
        let sibling = regions
            .iter()
            .find(|region| region.role == RegionRole::Mask)
            .expect("the sibling region");
        assert!(!sibling.reveal_on_answer, "the sibling stays masked");
        assert_eq!(
            "diagram labels: …, …", alt,
            "pre-reveal accessible text names NO label"
        );
        assert!(
            !alt.contains("Cache"),
            "the id channel must not speak the answer"
        );
        assert_eq!(
            &Some("diagram labels: …, Cache".to_string()),
            revealed_alt,
            "post-reveal exposes only the asked label; the sibling stays masked"
        );
    }

    #[test]
    fn an_unbound_span_or_invalid_geometry_falls_back_to_masked_source() {
        // The span binds the stream's FIRST occurrence of `Cache`: the node
        // id, which is no label's source range.
        let text = concat!(
            "## q\n",
            "```mermaid\n",
            "flowchart LR\n",
            "  Cache[store] --> B[Cache]\n",
            "```\n",
            "<!-- blank: span hidden=\"Cache\" -->\n",
        );
        let mut cards = crate::parser::parse_str("t.md", text).unwrap();
        let card = &mut cards[0];
        card.resolved_diagrams = vec![masked_fence_geometry(Vec::new())];
        let view = CardView::from(&*card);
        let ContentUnit::Code { lines } = &view.context_units[0] else {
            panic!(
                "an id-position span falls back to source: {:?}",
                view.context_units
            );
        };
        assert_eq!(
            vec![
                "flowchart LR".to_string(),
                "  ⍰[store] --> B[Cache]".to_string(),
            ],
            *lines,
            "the asked source span stays masked in the fallback"
        );

        // An UNRELATED label's hostile range fails the whole geometry before
        // anything slices, even though the asked span's own label is fine.
        let mut cards = masked_fence_deck();
        let card = cards
            .iter_mut()
            .find(|card| card.back == ["Cache"])
            .expect("the card asking the Cache label");
        card.resolved_diagrams = vec![masked_fence_geometry(vec![crate::diagram::GeometryLabel {
            id: "X".into(),
            text: "ghost".into(),
            source: crate::diagram::LabelSource::Range {
                start: 0,
                end: 9999,
            },
            bounds: crate::diagram::PixelBox {
                x: 0,
                y: 0,
                width: 1,
                height: 1,
            },
        }])];
        let view = CardView::from(&*card);
        let ContentUnit::Code { lines } = &view.context_units[0] else {
            panic!(
                "an out-of-bounds unrelated range falls back to source: {:?}",
                view.context_units
            );
        };
        assert_eq!(
            vec![
                "flowchart LR".to_string(),
                "  Cache[⬚] --> B[⍰]".to_string(),
            ],
            *lines,
            "asked and sibling source spans stay masked in the fallback"
        );
    }

    #[test]
    fn a_plain_cards_cover_reveals_with_the_answer() {
        let text = "## marque\n![](car.png)\n<!-- cover: rect x=1 y=2 width=3 height=4 -->\n\n---\nBMW\n<!-- id: card-autosautosautosautosauto -->\n";
        let cards = crate::parser::parse_str("t.md", text).unwrap();
        let plain = &cards[0];
        assert!(
            plain.region.is_none(),
            "a cover-only block keeps its plain card"
        );
        let view = CardView::from(plain);
        let cover = &view.images[0].regions[0];
        assert_eq!(RegionRole::Cover, cover.role);
        assert!(
            cover.reveal_on_answer,
            "a plain card has no sibling questions to protect, so its cover reveals"
        );
    }

    #[test]
    fn a_blank_cards_cover_stays_masked_to_protect_its_sibling_question() {
        let text = "## diagram\n![](parts.png)\n<!-- cover: rect x=1 y=2 width=3 height=4 -->\n\n---\nThe first is alpha; the second is beta.\n<!-- blank: span hidden=\"alpha\" b:a1b2c3 -->\n<!-- blank: span hidden=\"beta\" b:d4e5f6 -->\n";
        let cards = crate::parser::parse_str("t.md", text).unwrap();
        assert_eq!(2, cards.len(), "the block produces sibling span cards");

        for card in &cards {
            assert!(
                card.is_blank_card(),
                "this is a blank card, not a plain card"
            );
            let cover = &CardView::from(card).images[0].regions[0];
            assert_eq!(RegionRole::Cover, cover.role);
            assert!(
                !cover.reveal_on_answer,
                "answering one span must not uncover material that protects its sibling question"
            );
        }
    }

    const MULTI: &str =
        "---\nchoices: multiple\n---\n## evens\n- [x] 2\n- [x] 4\n- [ ] 3\n- [ ] 5\n";

    #[test]
    fn a_multiple_card_serves_its_full_option_set_and_flags_the_wire() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(MULTI);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let s = state(&session, &store, &augment, Some(NOW));
        let options = s
            .choices
            .expect("an authored multiple card builds its pick");
        assert_eq!(
            4,
            options.len(),
            "both corrects and both distractors: {options:?}"
        );
        assert_eq!(Some(true), s.choices_multiple);
        assert_eq!(Mode::Choice, s.mode);
    }

    #[test]
    fn choose_multi_passes_only_the_exact_correct_set() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(MULTI);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        let q = current_question(&session, &store, &augment).expect("multi question");
        assert!(q.multiple);
        let correct = q.correct_set.clone();
        assert_eq!(2, correct.len());

        let exact = choose_multi(&session, &store, &augment, &correct).unwrap();
        assert!(exact.passed, "exact set passes");
        assert_eq!(correct, exact.correct);

        let mut noisy: Vec<usize> = correct.iter().rev().copied().collect();
        noisy.push(correct[0]);
        let normalized = choose_multi(&session, &store, &augment, &noisy).unwrap();
        assert!(
            normalized.passed,
            "order and duplicates normalize before grading"
        );
        assert_eq!(
            correct, normalized.chosen,
            "feedback echoes the normalized set"
        );

        assert!(
            !choose_multi(&session, &store, &augment, &correct[..1])
                .unwrap()
                .passed,
            "a subset fails"
        );
        let distractor = (0..q.options.len()).find(|i| !correct.contains(i)).unwrap();
        let mut superset = correct.clone();
        superset.push(distractor);
        assert!(
            !choose_multi(&session, &store, &augment, &superset)
                .unwrap()
                .passed,
            "a superset fails"
        );
        assert!(
            choose_multi(&session, &store, &augment, &[q.options.len()]).is_none(),
            "an out-of-range index is refused, not graded"
        );
    }

    #[test]
    fn single_and_multi_picks_refuse_each_others_questions() {
        let (mut store, augment, _dir) = fixtures();
        let cards = parse(MULTI);
        seen(&mut store, &cards);
        let session = session_at(cards, &mut store, Depth::Recognize, NOW);
        assert!(
            choose(&session, &store, &augment, 0).is_none(),
            "a single pick against a select-all question is refused"
        );

        let (mut store2, mut augment2, _dir2) = fixtures();
        let single = parse(FOUR);
        seen(&mut store2, &single);
        arm(&mut augment2, &single);
        let single_session = session_at(single, &mut store2, Depth::Recognize, NOW);
        assert!(
            choose_multi(&single_session, &store2, &augment2, &[0]).is_none(),
            "a multi pick against a single question is refused"
        );
    }

    #[test]
    fn a_distractorless_multiple_card_serves_no_pick() {
        let (store, augment, _dir) = fixtures();
        let mut fresh_store = Store::open(_dir.path().join("fresh.json")).unwrap();
        let cards = parse("---\nchoices: multiple\n---\n## all\n- [x] a\n- [x] b\n");
        let session = session_at(cards, &mut fresh_store, Depth::Recall, NOW);
        let s = state(&session, &fresh_store, &augment, Some(NOW));
        assert!(s.introducing);
        assert_eq!(None, s.choices, "nothing to choose against, so no pick");
        assert_eq!(None, s.choices_multiple);
        drop(store);
    }
}