alix 0.5.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
//! User configuration, loaded from a TOML file
//! (`~/.config/alix/config.toml` on Linux).
//!
//! Currently this configures key bindings. Every action takes a list of
//! keys; the first one is shown in the web review page's footer. A key is written
//! as a single character (`"j"`), a special key name (`"space"`, `"enter"`,
//! `"tab"`, `"esc"`, `"backspace"`), or either with a `ctrl-` prefix
//! (`"ctrl-s"`).
//!
//! Plain-character bindings are ignored while you are typing an answer
//! (typing and typeline mode), so they cannot shadow text input; use `ctrl-` or
//! special keys for actions that must be reachable there (hint, skip, quit).

use std::{
    fmt,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, bail};
use serde::Deserialize;

/// A key without modifiers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Key {
    Char(char),
    Enter,
    Tab,
    Esc,
    Backspace,
}

/// A key plus the Ctrl modifier flag; what a binding matches against.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KeyPattern {
    pub key: Key,
    pub ctrl: bool,
}

impl KeyPattern {
    /// `true` if this pattern would swallow plain text input.
    pub fn is_plain_char(&self) -> bool {
        matches!(self.key, Key::Char(_)) && !self.ctrl
    }
}

impl fmt::Display for KeyPattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ctrl {
            write!(f, "Ctrl-")?;
        }
        match self.key {
            Key::Char(' ') => write!(f, "SPACE"),
            // After "Ctrl-" the letter reads better uppercased (Ctrl-S).
            Key::Char(c) if self.ctrl => write!(f, "{}", c.to_uppercase()),
            Key::Char(c) => write!(f, "{c}"),
            Key::Enter => write!(f, "ENTER"),
            Key::Tab => write!(f, "TAB"),
            Key::Esc => write!(f, "ESC"),
            Key::Backspace => write!(f, "BACKSPACE"),
        }
    }
}

/// Parses a key description like `"j"`, `"space"` or `"ctrl-s"`.
pub fn parse_key(s: &str) -> Result<KeyPattern> {
    let lower = s.trim().to_lowercase();
    let (ctrl, name) = match lower.strip_prefix("ctrl-") {
        Some(rest) => (true, rest),
        None => (false, lower.as_str()),
    };
    let key = match name {
        "space" => Key::Char(' '),
        "enter" | "return" => Key::Enter,
        "tab" => Key::Tab,
        "esc" | "escape" => Key::Esc,
        "backspace" => Key::Backspace,
        _ => {
            let mut chars = name.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) => Key::Char(c),
                _ => bail!(
                    "invalid key {s:?}: expected a single character, \
                     space/enter/tab/esc/backspace, or a ctrl- prefix"
                ),
            }
        }
    };
    Ok(KeyPattern { key, ctrl })
}

/// All rebindable actions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Bindings {
    /// Self-graded modes: grade as failed (FSRS `Again` — resets learning progress).
    pub failed: Vec<KeyPattern>,
    /// Self-graded modes: grade as partly (FSRS `Hard` — a weak pass, still drilling).
    pub partly: Vec<KeyPattern>,
    /// Self-graded modes: grade as passed (FSRS `Good` — advances toward graduation).
    pub passed: Vec<KeyPattern>,
    /// Recognition (multiple-choice) and key-point review: move the focus up or
    /// down the list of choices or points. The arrow keys always work too.
    pub up: Vec<KeyPattern>,
    pub down: Vec<KeyPattern>,
    /// Flip mode: reveal the answer.
    pub reveal: Vec<KeyPattern>,
    /// Typing mode: reveal a hint (fails the card).
    pub hint: Vec<KeyPattern>,
    /// TypeLine mode: submit the current line.
    pub submit: Vec<KeyPattern>,
    /// Put the current card at the end of the queue without grading.
    pub skip: Vec<KeyPattern>,
    /// Mark the current card for removal from its deck file (applied when the
    /// session ends).
    pub remove: Vec<KeyPattern>,
    /// Promote the current virtual (remediation) card into its deck file,
    /// dropping the virtual copy — the new deck card carries over its review
    /// schedule rather than starting fresh. Offered only while reviewing a
    /// virtual card.
    pub promote: Vec<KeyPattern>,
    /// Leave the feedback screen.
    pub cont: Vec<KeyPattern>,
    /// Start a new session from the summary screen.
    pub restart: Vec<KeyPattern>,
    /// Open the ask-Claude view on an answered card.
    pub ask: Vec<KeyPattern>,
    /// Ask view: condense the conversation into a note on the card
    /// ("Make this a note").
    pub make_note: Vec<KeyPattern>,
    /// Ask view: distill the conversation into a draft card ("Make this a
    /// card"; adult review only).
    pub make_card: Vec<KeyPattern>,
    /// Quit the session.
    pub quit: Vec<KeyPattern>,
}

impl Default for Bindings {
    fn default() -> Self {
        let keys = |list: &[&str]| list.iter().map(|s| parse_key(s).unwrap()).collect();
        Self {
            failed: keys(&["1", "f"]),
            partly: keys(&["2", "p"]),
            passed: keys(&["3", "n"]),
            up: keys(&["k"]),
            down: keys(&["j"]),
            reveal: keys(&["space", "enter"]),
            hint: keys(&["tab", "ctrl-h", "ctrl-backspace"]),
            submit: keys(&["enter"]),
            skip: keys(&["ctrl-s"]),
            remove: keys(&["ctrl-x"]),
            promote: keys(&["ctrl-p"]),
            cont: keys(&["enter", "space"]),
            restart: keys(&["r"]),
            ask: keys(&["?"]),
            make_note: keys(&["ctrl-n"]),
            make_card: keys(&["ctrl-d"]),
            quit: keys(&["esc", "ctrl-c"]),
        }
    }
}

impl Bindings {
    /// The key shown in the footer for an action (its first binding).
    pub fn label(list: &[KeyPattern]) -> String {
        list.first()
            .map(|p| p.to_string())
            .unwrap_or_else(|| "?".to_string())
    }
}

/// Rebindable navigation keys for the deck picker, configured in the
/// `[keys.picker]` section. Vim-style by default. The arrow keys, `Enter` (open)
/// and `Esc` (back) always work regardless of these; jumping to the first/last
/// row stays fixed at `g`/`G`/Home/End (letter bindings are case-insensitive, so
/// `g` and `G` can't be told apart — same as the `[keys.browse]` pager).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickerKeys {
    /// Move up / down the list.
    pub up: Vec<KeyPattern>,
    pub down: Vec<KeyPattern>,
    /// Open the focused row (a deck reviews, a workspace drills in).
    pub open: Vec<KeyPattern>,
    /// Step back / cancel.
    pub back: Vec<KeyPattern>,
    /// Enter filter mode.
    pub filter: Vec<KeyPattern>,
    /// Open the Mastered window.
    pub mastered: Vec<KeyPattern>,
    /// Open (or close) the focused deck's depth menu — the split Learn
    /// button's â–¾. `Esc` always closes it too.
    pub depth: Vec<KeyPattern>,
    /// Start the focused deck at a depth while its menu is open. `Enter`
    /// always starts the highlighted (last-used) depth.
    pub recognize: Vec<KeyPattern>,
    pub recall: Vec<KeyPattern>,
    pub reconstruct: Vec<KeyPattern>,
    /// Toggle the depth menu's cram tick-box (include cards that aren't due).
    pub cram: Vec<KeyPattern>,
}

impl Default for PickerKeys {
    fn default() -> Self {
        let keys = |list: &[&str]| list.iter().map(|s| parse_key(s).unwrap()).collect();
        Self {
            up: keys(&["k"]),
            down: keys(&["j"]),
            open: keys(&["l"]),
            back: keys(&["h"]),
            filter: keys(&["/", "ctrl-f"]),
            mastered: keys(&["m"]),
            depth: keys(&["v"]),
            recognize: keys(&["1"]),
            recall: keys(&["2"]),
            reconstruct: keys(&["3"]),
            cram: keys(&["c"]),
        }
    }
}

/// Key bindings for the read-only Browse overlay, configured in the
/// `[keys.browse]` section. Jumping to the first/last card stays fixed at
/// `g`/`G`/Home/End — letter bindings are case-insensitive, so `g` and `G`
/// cannot be told apart — and the arrow keys always work for next/previous.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BrowseBindings {
    /// Move to the next card.
    pub next: Vec<KeyPattern>,
    /// Move to the previous card.
    pub prev: Vec<KeyPattern>,
    /// Mark the current card for removal from its deck file (applied on quit).
    pub remove: Vec<KeyPattern>,
    /// Leave the browser.
    pub quit: Vec<KeyPattern>,
}

impl Default for BrowseBindings {
    fn default() -> Self {
        let keys = |list: &[&str]| list.iter().map(|s| parse_key(s).unwrap()).collect();
        Self {
            next: keys(&["l", "n", "space"]),
            prev: keys(&["h", "p"]),
            remove: keys(&["x"]),
            quit: keys(&["q", "esc", "ctrl-c"]),
        }
    }
}

/// Which AI CLI backend to use for assistant calls.
///
/// All four variants are wired; `backend_for` returns `Ok` for each.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BackendKind {
    /// The Claude Code CLI (`claude -p`). The default.
    #[default]
    Claude,
    /// Google Gemini CLI (`gemini -p`, headless).
    Gemini,
    /// OpenAI Codex CLI (`codex exec`, headless).
    Codex,
    /// GitHub Copilot CLI (`copilot -p`, headless).
    Copilot,
}

/// Settings for the ask-Claude integration (`[ask]` in the config file).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AskConfig {
    /// Which AI CLI backend to use.
    pub backend: BackendKind,
    /// The CLI executable to run.
    pub command: String,
    /// Model passed as `--model`; `None` uses the CLI's own default.
    pub model: Option<String>,
    /// `--effort` level (`low`/`medium`/`high`/`xhigh`/`max`); `None` omits the
    /// flag and uses the CLI's default. Trace operations default this to
    /// `high`.
    pub effort: Option<String>,
    /// How long to wait for an answer before giving up.
    pub timeout_secs: u64,
    /// `--permission-mode` for the headless CLI. The default `"dontAsk"`
    /// silently denies any tool not in `allowed_tools` instead of waiting
    /// for an interactive approval that `-p` mode cannot provide (which
    /// would hang). An empty string omits the flag.
    pub permission_mode: String,
    /// Tools the assistant may use (`--allowedTools`). Combined with
    /// `dontAsk`, this is an exclusive allowlist: everything else is denied,
    /// so a malicious deck-link page cannot make the tutor run commands.
    pub allowed_tools: Vec<String>,
    /// Working directory for the CLI process (`current_dir`). `None` inherits
    /// the caller's. Not a user setting: trace building sets it to the
    /// `% source:` root so Claude explores the source with relative paths.
    pub cwd: Option<PathBuf>,
    /// Opt-in: let the ask-Claude tutor **read the card's source** to verify its
    /// answer (Read/Glob/Grep, working directory at the deck's `% source:`
    /// project root) instead of answering from memory. Off by default because it
    /// grants the served tutor file-read access — only enable it on a machine and
    /// network you trust (especially with `alix --lan`).
    pub source_access: bool,
    /// Source-tree byte threshold for the pre-flight size guard. When a local
    /// source tree (for `alix generate` in all its forms)
    /// exceeds this many bytes, `alix` warns and asks for confirmation before
    /// spending a potentially large model call. Default is 5 MB (5_000_000 bytes).
    /// Set to 0 to disable the guard (always proceed without confirming).
    pub preflight_threshold: u64,
}

impl Default for AskConfig {
    fn default() -> Self {
        Self {
            backend: BackendKind::Claude,
            command: "claude".to_string(),
            model: None,
            effort: None,
            timeout_secs: 120,
            permission_mode: "dontAsk".to_string(),
            allowed_tools: vec!["WebFetch".to_string(), "WebSearch".to_string()],
            cwd: None,
            source_access: false,
            preflight_threshold: 5_000_000,
        }
    }
}

/// Settings for AI deck generation (`alix deck`, the `[generate]` section).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GenerateDeckConfig {
    /// Model passed as `--model`; `None` falls back to the `[ask]` model, then
    /// the CLI's own default.
    pub model: Option<String>,
    /// How long to wait for the deck before giving up (generation is a bigger
    /// call than a single question, so this is larger than the ask timeout).
    pub timeout_secs: u64,
    /// Upper bound on the number of cards to generate.
    pub max_cards: usize,
    /// Extra guidance appended to the instruction prompt (the common way to
    /// tweak generation, e.g. "focus on the public API").
    pub extra: Option<String>,
    /// A full replacement for the built-in instruction prompt. May use the
    /// `{url}` and `{max_cards}` placeholders.
    pub prompt: Option<String>,
    /// Run a second Claude pass that reviews the draft and removes redundant
    /// cards. `--review` forces it on for a single run.
    pub review: bool,
}

impl Default for GenerateDeckConfig {
    fn default() -> Self {
        Self {
            model: None,
            timeout_secs: 300,
            max_cards: 30,
            extra: None,
            prompt: None,
            review: false,
        }
    }
}

/// How strictly the AI exam grades a typed answer against a question's rubric
/// points. This is a per-deck choice (set with `% strictness:`, the `[exam]`
/// default, or `alix exam --strictness`) because some material demands
/// recalling everything while other material is about grasping the idea.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "full", derive(clap::ValueEnum))]
pub enum Strictness {
    /// Completeness required: every rubric point must be present, so omitting
    /// one is a gap. For procedures, exact syntax, security — where knowing
    /// most of it isn't enough.
    Strict,
    /// Judge understanding, not phrasing: a point is covered if the answer
    /// shows the student grasps it (even briefly, in their own words); only
    /// a wrong or genuinely-absent idea is a gap.
    #[default]
    Balanced,
    /// Benefit of the doubt: only clearly wrong or unanswered points are gaps.
    /// For breadth or casual learning.
    Lenient,
}

impl Strictness {
    /// Parses the config value name (case-insensitive), mirroring the clap
    /// value names; the gated parity test keeps the two in step.
    pub fn parse(value: &str) -> Option<Self> {
        match value.to_ascii_lowercase().as_str() {
            "strict" => Some(Self::Strict),
            "balanced" => Some(Self::Balanced),
            "lenient" => Some(Self::Lenient),
            _ => None,
        }
    }
}

/// Settings for the AI exam (`alix exam`, the `[exam]` section). Like
/// generate, it reuses the `[ask]` command, permission mode and tool allowlist
/// (WebFetch reads a `% source:` URL). The exam grades open understanding
/// questions generated from the deck's `% source:`, never the cards.
#[derive(Clone, Debug, PartialEq)]
pub struct ExamConfig {
    /// Model passed as `--model`; `None` falls back to the `[ask]` model, then
    /// the CLI's own default.
    pub model: Option<String>,
    /// How long to wait for each exam call (question generation, grading and
    /// remediation are bigger calls than a single question, like generate).
    pub timeout_secs: u64,
    /// How many questions a sitting asks.
    pub num_questions: usize,
    /// Fraction of questions that must be a full Pass for the exam to pass
    /// (1.0 = every question, the v1 default).
    pub pass_threshold: f64,
    /// How strictly each typed answer is graded against the rubric.
    pub strictness: Strictness,
    /// How long (seconds) a *failed* trace exam blocks a re-sit, so the graded
    /// feedback can't be pasted straight back into the one fixed question.
    /// `0` disables the cooldown. Trace exams only (a fact exam regenerates
    /// fresh questions each sitting).
    pub retry_cooldown_secs: u64,
    /// Extra guidance appended to the question-generation prompt (e.g. "focus
    /// on the borrow checker").
    pub extra: Option<String>,
}

impl Default for ExamConfig {
    fn default() -> Self {
        Self {
            model: None,
            timeout_secs: 300,
            num_questions: 5,
            pass_threshold: 1.0,
            strictness: Strictness::default(),
            retry_cooldown_secs: 3600,
            extra: None,
        }
    }
}

/// Settings for trace building and exploration (the `[trace]` section).
/// Building explores the deck's `% source:` to discover the path, so — unlike
/// the other AI calls — it runs the CLI with **read-only** file tools (`Read`,
/// `Glob`, `Grep`, plus `WebFetch` for a URL source) and the source root as the
/// working directory. No write or shell tool is ever granted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TraceConfig {
    /// Model passed as `--model`. Left unset by default so each backend picks
    /// its own strong model for trace ([`Backend::default_trace_model`] — Claude
    /// → `opus`); an explicit value here or in `[ask]` overrides it. Trace
    /// building is agentic, correctness-critical and one-shot, so it wants the
    /// strong model rather than the CLI's cheap default.
    ///
    /// [`Backend::default_trace_model`]: crate::backend::Backend::default_trace_model
    pub model: Option<String>,
    /// `--effort` level; defaults to `"high"` for the same reason. `None` omits
    /// the flag. Shared by `--build`, `--suggest` and `--grade`.
    pub effort: Option<String>,
    /// How long to wait for the build before giving up. Exploring a source and
    /// tracing a path is the biggest call, so this is larger than the others.
    pub timeout_secs: u64,
    /// Extra guidance appended to the build prompt (e.g. "trace the read path,
    /// not the write path").
    pub extra: Option<String>,
    /// Have the AI grade each walk prediction against the checkpoint's key
    /// points instead of self-grading (a model call per hop — opt-in).
    pub auto_grade: bool,
}

impl Default for TraceConfig {
    fn default() -> Self {
        Self {
            // Trace building is one-shot, amortized over many reviews, and a weak
            // model fails silently (a parseable but loose chain), so it wants a
            // strong model + high effort. The *model* is left unset here so each
            // backend picks its own strong model (`Backend::default_trace_model`);
            // effort still defaults high across backends.
            model: None,
            effort: Some("high".to_string()),
            timeout_secs: 600,
            extra: None,
            auto_grade: false,
        }
    }
}

/// Settings for `alix deck augment` (the `[ai]` section). Augmentation is a
/// deliberate command — it generates distractors (and, later, notes) into the
/// sidecar cache — so there is no on/off switch; these just tune the calls.
/// Generation reuses the `[ask]` command but runs tool-free, so no allowlist
/// applies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AiConfig {
    /// Model passed as `--model`; `None` falls back to the `[ask]` model, then
    /// the CLI's own default.
    pub model: Option<String>,
    /// How many distractors to request per choice card.
    pub distractor_count: usize,
    /// How many reworded question variants to request per card.
    pub variant_count: usize,
    /// The most key points to request when decomposing a card's answer (the
    /// Explain-mode checklist rubric).
    pub keypoint_count: usize,
    /// How long to wait for a generation call before giving up. A whole-deck
    /// batch is a big call (like `[generate]`/`[exam]`), so this is generous.
    pub timeout_secs: u64,
}

impl Default for AiConfig {
    fn default() -> Self {
        Self {
            model: None,
            distractor_count: 3,
            variant_count: 4,
            keypoint_count: 5,
            timeout_secs: 300,
        }
    }
}

/// Which served frontend `/` returns: the adult app (`review.html`) or the
/// kid-facing one. Also selects the ask-tutor's system preamble — kid-safe
/// wording for `Kids`, the existing dev-facing wording for `Adult`
/// (`ask::question_prompt`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Audience {
    #[default]
    Adult,
    Kids,
}

/// Settings for the web server bare `alix` starts (the `[serve]` section).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServeConfig {
    /// Default port to listen on (overridden by `--port`).
    pub port: u16,
    /// Optional pairing token. When set (or auto-generated for `--lan`), the web
    /// server requires it on `/api/*` — see `alix --lan`.
    pub token: Option<String>,
    /// Which frontend `/` serves.
    pub audience: Audience,
}

impl Default for ServeConfig {
    fn default() -> Self {
        Self {
            port: 7777,
            token: None,
            audience: Audience::default(),
        }
    }
}

/// The whole user configuration.
// Not `Eq`: `ExamConfig::pass_threshold` is an `f64`.
/// Personal review pacing (`[review]` in the config): the FSRS retention target and
/// the interval past which a card retires. A workspace can override these in its own
/// `alix.local.toml` (never shared).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ReviewConfig {
    /// FSRS target retrievability `r` (0.70–0.99). Higher → shorter intervals.
    pub retention: f64,
    /// A card retires once its scheduled interval reaches this many days; `None`
    /// disables retirement (drill forever).
    pub retire_after_days: Option<u32>,
    /// Settle gap (ms) between acquiring a card and its first quiz; also the
    /// session's same-card re-serve floor. `0` disables both gaps.
    pub acquire_cooldown_ms: u64,
    /// Max new (never-seen) cards a session introduces. `None` = unset here —
    /// the launcher resolves `--new` > this > its built-in default.
    pub max_new: Option<usize>,
    /// Session size cap. `None` = unset (no cap unless `--limit` says so).
    pub limit: Option<usize>,
    /// A personal per-workspace target date ("ready by <date>", inclusive),
    /// set ONLY via a workspace's `alix.local.toml`; never global.
    pub deadline: Option<chrono::NaiveDate>,
    /// How many days before the deadline the retention ramp starts
    /// (`deadline_ramp`); 0 = interval cap only. Meaningless without `deadline`.
    pub deadline_ramp_days: u32,
}

impl Default for ReviewConfig {
    fn default() -> Self {
        Self {
            retention: 0.9,
            retire_after_days: Some(crate::session::DEFAULT_RETIRE_AFTER_DAYS),
            acquire_cooldown_ms: crate::scheduler::DEFAULT_ACQUIRE_COOLDOWN_MS,
            max_new: None,
            limit: None,
            deadline: None,
            deadline_ramp_days: 14,
        }
    }
}

/// A workspace's personal, unshared pacing override (sibling of `alix.toml`).
pub const LOCAL_MANIFEST: &str = "alix.local.toml";

impl ReviewConfig {
    /// Overlays a workspace's `alix.local.toml` `[review]` overrides onto this
    /// (global) config: only the keys present in the local file win. A missing or
    /// malformed file leaves the config unchanged. This file is personal and is
    /// never shared — deliberately separate from the shared `alix.toml`.
    pub fn for_workspace(self, workspace_dir: &Path) -> Self {
        let Ok(text) = std::fs::read_to_string(workspace_dir.join(LOCAL_MANIFEST)) else {
            return self;
        };
        let Ok(raw) = toml::from_str::<RawLocalConfig>(&text) else {
            return self;
        };
        let mut review = self;
        if let Some(retention) = raw.review.retention {
            review.retention = retention.clamp(MIN_RETENTION, MAX_RETENTION);
        }
        if let Some(retire_after) = raw.review.retire_after
            && let Ok(days) = parse_retire_after(&retire_after)
        {
            review.retire_after_days = days;
        }
        if let Some(cooldown) = raw.review.acquire_cooldown
            && let Ok(ms) = parse_acquire_cooldown(&cooldown)
        {
            review.acquire_cooldown_ms = ms;
        }
        if let Some(n) = raw.review.max_new {
            review.max_new = Some(n);
        }
        if let Some(n) = raw.review.limit {
            review.limit = Some(n);
        }
        // The deadline overlay applies only inside a real workspace (manifest
        // present): outside one, a deadline has no chip, no web action, and no
        // doctor lint to explain why retention is quietly ramping — a trap, not a
        // feature. Pacing knobs above have no such visible product surface, so they
        // stay folder-friendly. Checked once here (not per key) against the same
        // `is_workspace` definition the picker/serve/doctor use, so the config
        // layer can't drift from them.
        if crate::workspace::is_workspace(workspace_dir) {
            if let Some(date) = raw.review.deadline
                && let Ok(d) = chrono::NaiveDate::parse_from_str(&date, "%Y-%m-%d")
            {
                review.deadline = Some(d);
            }
            if let Some(ramp) = raw.review.deadline_ramp
                && let Ok(days) = parse_ramp_days(&ramp)
            {
                review.deadline_ramp_days = days;
            }
        }
        review
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Config {
    pub keys: Bindings,
    /// Navigation keys for the deck picker.
    pub picker: PickerKeys,
    /// Key bindings for the Browse overlay.
    pub browse: BrowseBindings,
    pub ask: AskConfig,
    /// AI deck generation settings.
    pub generate: GenerateDeckConfig,
    /// AI exam settings.
    pub exam: ExamConfig,
    /// Trace building settings.
    pub trace: TraceConfig,
    /// Opt-in AI question-augmentation settings (choice-mode distractors).
    pub ai: AiConfig,
    /// Local web frontend settings.
    pub serve: ServeConfig,
    /// Personal review pacing (FSRS retention + retirement interval).
    pub review: ReviewConfig,
    /// Directory the startup picker lists decks from, and resolves bare deck
    /// names against. `None` uses [`default_decks_dir`].
    pub decks_dir: Option<PathBuf>,
}

impl Config {
    /// The decks directory to use (config value or the default `~/decks`).
    pub fn decks_dir(&self) -> Option<PathBuf> {
        self.decks_dir.clone().or_else(default_decks_dir)
    }
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    #[serde(default)]
    keys: RawKeys,
    #[serde(default)]
    ask: RawAsk,
    #[serde(default)]
    generate: RawGenerate,
    #[serde(default)]
    exam: RawExam,
    #[serde(default)]
    trace: RawTrace,
    #[serde(default)]
    ai: RawAi,
    #[serde(default)]
    serve: RawServe,
    #[serde(default)]
    review: RawReviewConfig,
    decks_dir: Option<String>,
}

/// The `[review]` section: personal pacing (FSRS retention, when a card retires).
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawReviewConfig {
    retention: Option<f64>,
    retire_after: Option<String>,
    acquire_cooldown: Option<String>,
    max_new: Option<usize>,
    limit: Option<usize>,
}

/// The `alix.local.toml` `[review]` section: everything the global section
/// accepts, plus the per-workspace deadline keys that are meaningless
/// globally.
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawLocalReviewConfig {
    retention: Option<f64>,
    retire_after: Option<String>,
    acquire_cooldown: Option<String>,
    max_new: Option<usize>,
    limit: Option<usize>,
    deadline: Option<String>,
    deadline_ramp: Option<String>,
}

/// The `alix.local.toml` schema: personal per-workspace overrides. Currently just
/// `[review]`; lenient (unknown top-level tables are ignored) so it can grow.
#[derive(Deserialize, Default)]
struct RawLocalConfig {
    #[serde(default)]
    review: RawLocalReviewConfig,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawAi {
    model: Option<String>,
    distractor_count: Option<usize>,
    variant_count: Option<usize>,
    keypoint_count: Option<usize>,
    timeout_secs: Option<u64>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawServe {
    port: Option<u16>,
    token: Option<String>,
    audience: Option<Audience>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawGenerate {
    model: Option<String>,
    timeout_secs: Option<u64>,
    max_cards: Option<usize>,
    extra: Option<String>,
    prompt: Option<String>,
    review: Option<bool>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawExam {
    model: Option<String>,
    timeout_secs: Option<u64>,
    num_questions: Option<usize>,
    pass_threshold: Option<f64>,
    strictness: Option<String>,
    retry_cooldown_secs: Option<u64>,
    extra: Option<String>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawTrace {
    model: Option<String>,
    effort: Option<String>,
    timeout_secs: Option<u64>,
    extra: Option<String>,
    auto_grade: Option<bool>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawPicker {
    up: Option<Vec<String>>,
    down: Option<Vec<String>>,
    open: Option<Vec<String>>,
    back: Option<Vec<String>>,
    filter: Option<Vec<String>>,
    mastered: Option<Vec<String>>,
    depth: Option<Vec<String>>,
    recognize: Option<Vec<String>>,
    recall: Option<Vec<String>>,
    reconstruct: Option<Vec<String>>,
    cram: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawBrowse {
    next: Option<Vec<String>>,
    prev: Option<Vec<String>>,
    remove: Option<Vec<String>>,
    quit: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawAsk {
    backend: Option<String>,
    command: Option<String>,
    model: Option<String>,
    effort: Option<String>,
    timeout_secs: Option<u64>,
    permission_mode: Option<String>,
    allowed_tools: Option<Vec<String>>,
    source_access: Option<bool>,
    preflight_threshold: Option<u64>,
}

/// The `[keys]` table: one subtable per surface (`[keys.review]`,
/// `[keys.picker]`, `[keys.browse]`), so every keybinding lives under `keys`.
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawKeys {
    #[serde(default)]
    review: RawReview,
    #[serde(default)]
    picker: RawPicker,
    #[serde(default)]
    browse: RawBrowse,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawReview {
    failed: Option<Vec<String>>,
    partly: Option<Vec<String>>,
    passed: Option<Vec<String>>,
    up: Option<Vec<String>>,
    down: Option<Vec<String>>,
    reveal: Option<Vec<String>>,
    hint: Option<Vec<String>>,
    submit: Option<Vec<String>>,
    skip: Option<Vec<String>>,
    remove: Option<Vec<String>>,
    promote: Option<Vec<String>>,
    r#continue: Option<Vec<String>>,
    restart: Option<Vec<String>>,
    ask: Option<Vec<String>>,
    make_note: Option<Vec<String>>,
    make_card: Option<Vec<String>>,
    quit: Option<Vec<String>>,
}

impl Config {
    /// Parses a configuration from TOML text. Actions that are not mentioned
    /// keep their default bindings; an empty list disables an action.
    pub fn from_toml(text: &str) -> Result<Self> {
        let raw: RawConfig = toml::from_str(text).context("invalid config file")?;
        let mut keys = Bindings::default();

        let assign = |target: &mut Vec<KeyPattern>,
                      source: Option<Vec<String>>,
                      action: &str|
         -> Result<()> {
            if let Some(list) = source {
                *target = list
                    .iter()
                    .map(|s| parse_key(s).with_context(|| format!("in binding for {action:?}")))
                    .collect::<Result<_>>()?;
            }
            Ok(())
        };

        let review = raw.keys.review;
        assign(&mut keys.failed, review.failed, "review.failed")?;
        assign(&mut keys.partly, review.partly, "review.partly")?;
        assign(&mut keys.passed, review.passed, "review.passed")?;
        assign(&mut keys.up, review.up, "review.up")?;
        assign(&mut keys.down, review.down, "review.down")?;
        assign(&mut keys.reveal, review.reveal, "review.reveal")?;
        assign(&mut keys.hint, review.hint, "review.hint")?;
        assign(&mut keys.submit, review.submit, "review.submit")?;
        assign(&mut keys.skip, review.skip, "review.skip")?;
        assign(&mut keys.remove, review.remove, "review.remove")?;
        assign(&mut keys.promote, review.promote, "review.promote")?;
        assign(&mut keys.cont, review.r#continue, "review.continue")?;
        assign(&mut keys.restart, review.restart, "review.restart")?;
        assign(&mut keys.ask, review.ask, "review.ask")?;
        assign(&mut keys.make_note, review.make_note, "review.make_note")?;
        assign(&mut keys.make_card, review.make_card, "review.make_card")?;
        assign(&mut keys.quit, review.quit, "review.quit")?;

        let mut picker = PickerKeys::default();
        assign(&mut picker.up, raw.keys.picker.up, "picker.up")?;
        assign(&mut picker.down, raw.keys.picker.down, "picker.down")?;
        assign(&mut picker.open, raw.keys.picker.open, "picker.open")?;
        assign(&mut picker.back, raw.keys.picker.back, "picker.back")?;
        assign(&mut picker.filter, raw.keys.picker.filter, "picker.filter")?;
        assign(
            &mut picker.mastered,
            raw.keys.picker.mastered,
            "picker.mastered",
        )?;
        assign(&mut picker.depth, raw.keys.picker.depth, "picker.depth")?;
        assign(
            &mut picker.recognize,
            raw.keys.picker.recognize,
            "picker.recognize",
        )?;
        assign(&mut picker.recall, raw.keys.picker.recall, "picker.recall")?;
        assign(
            &mut picker.reconstruct,
            raw.keys.picker.reconstruct,
            "picker.reconstruct",
        )?;
        assign(&mut picker.cram, raw.keys.picker.cram, "picker.cram")?;

        let mut browse = BrowseBindings::default();
        assign(&mut browse.next, raw.keys.browse.next, "browse.next")?;
        assign(&mut browse.prev, raw.keys.browse.prev, "browse.prev")?;
        assign(&mut browse.remove, raw.keys.browse.remove, "browse.remove")?;
        assign(&mut browse.quit, raw.keys.browse.quit, "browse.quit")?;

        let mut ask = AskConfig::default();
        if let Some(b) = raw.ask.backend.filter(|s| !s.trim().is_empty()) {
            ask.backend = match b.trim().to_ascii_lowercase().as_str() {
                "claude" => BackendKind::Claude,
                "gemini" => BackendKind::Gemini,
                "codex" => BackendKind::Codex,
                "copilot" => BackendKind::Copilot,
                _ => bail!("invalid ask.backend {b:?}: expected claude, gemini, codex, or copilot"),
            };
        }
        if let Some(command) = raw.ask.command {
            ask.command = command;
        }
        // An empty model string means "use the CLI default", like absence.
        if let Some(model) = raw.ask.model.filter(|m| !m.trim().is_empty()) {
            ask.model = Some(model);
        }
        if let Some(effort) = raw.ask.effort.filter(|e| !e.trim().is_empty()) {
            ask.effort = Some(effort);
        }
        if let Some(secs) = raw.ask.timeout_secs {
            ask.timeout_secs = secs;
        }
        if let Some(mode) = raw.ask.permission_mode {
            ask.permission_mode = mode;
        }
        if let Some(tools) = raw.ask.allowed_tools {
            ask.allowed_tools = tools;
        }
        if let Some(source_access) = raw.ask.source_access {
            ask.source_access = source_access;
        }
        if let Some(threshold) = raw.ask.preflight_threshold {
            ask.preflight_threshold = threshold;
        }

        let mut generate = GenerateDeckConfig::default();
        if let Some(model) = raw.generate.model.filter(|m| !m.trim().is_empty()) {
            generate.model = Some(model);
        }
        if let Some(secs) = raw.generate.timeout_secs {
            generate.timeout_secs = secs;
        }
        if let Some(max) = raw.generate.max_cards {
            generate.max_cards = max;
        }
        generate.extra = raw.generate.extra.filter(|s| !s.trim().is_empty());
        generate.prompt = raw.generate.prompt.filter(|s| !s.trim().is_empty());
        if let Some(review) = raw.generate.review {
            generate.review = review;
        }

        let mut exam = ExamConfig::default();
        if let Some(model) = raw.exam.model.filter(|m| !m.trim().is_empty()) {
            exam.model = Some(model);
        }
        if let Some(secs) = raw.exam.timeout_secs {
            exam.timeout_secs = secs;
        }
        if let Some(n) = raw.exam.num_questions {
            exam.num_questions = n;
        }
        if let Some(t) = raw.exam.pass_threshold {
            exam.pass_threshold = t;
        }
        if let Some(secs) = raw.exam.retry_cooldown_secs {
            exam.retry_cooldown_secs = secs;
        }
        if let Some(s) = raw.exam.strictness.filter(|s| !s.trim().is_empty()) {
            match Strictness::parse(s.trim()) {
                Some(v) => exam.strictness = v,
                None => {
                    bail!("invalid exam.strictness {s:?}: expected strict, balanced, or lenient")
                }
            }
        }
        exam.extra = raw.exam.extra.filter(|s| !s.trim().is_empty());

        let mut trace = TraceConfig::default();
        if let Some(model) = raw.trace.model.filter(|m| !m.trim().is_empty()) {
            trace.model = Some(model);
        }
        if let Some(effort) = raw.trace.effort.filter(|e| !e.trim().is_empty()) {
            trace.effort = Some(effort);
        }
        if let Some(secs) = raw.trace.timeout_secs {
            trace.timeout_secs = secs;
        }
        trace.extra = raw.trace.extra.filter(|s| !s.trim().is_empty());
        if let Some(auto_grade) = raw.trace.auto_grade {
            trace.auto_grade = auto_grade;
        }

        let mut ai = AiConfig::default();
        if let Some(model) = raw.ai.model.filter(|m| !m.trim().is_empty()) {
            ai.model = Some(model);
        }
        if let Some(count) = raw.ai.distractor_count {
            ai.distractor_count = count;
        }
        if let Some(count) = raw.ai.variant_count {
            ai.variant_count = count;
        }
        if let Some(count) = raw.ai.keypoint_count {
            ai.keypoint_count = count;
        }
        if let Some(secs) = raw.ai.timeout_secs {
            ai.timeout_secs = secs;
        }

        let mut serve = ServeConfig::default();
        if let Some(port) = raw.serve.port {
            serve.port = port;
        }
        serve.token = raw.serve.token;
        if let Some(audience) = raw.serve.audience {
            serve.audience = audience;
        }

        let mut review = ReviewConfig::default();
        if let Some(retention) = raw.review.retention {
            review.retention = retention.clamp(MIN_RETENTION, MAX_RETENTION);
        }
        if let Some(retire_after) = raw.review.retire_after {
            review.retire_after_days =
                parse_retire_after(&retire_after).context("in [review] retire_after")?;
        }
        if let Some(cooldown) = raw.review.acquire_cooldown {
            review.acquire_cooldown_ms =
                parse_acquire_cooldown(&cooldown).context("in [review] acquire_cooldown")?;
        }
        review.max_new = raw.review.max_new;
        review.limit = raw.review.limit;

        let decks_dir = raw.decks_dir.map(|s| expand_tilde(&s));

        Ok(Self {
            keys,
            picker,
            browse,
            ask,
            generate,
            exam,
            trace,
            ai,
            serve,
            review,
            decks_dir,
        })
    }

    /// Loads the configuration.
    ///
    /// With an explicit `path` the file must exist. Without one, the default
    /// location is used if present, otherwise the default configuration is
    /// returned.
    pub fn load(path: Option<&Path>) -> Result<Self> {
        let path = match path {
            Some(path) => path.to_path_buf(),
            None => match default_config_path() {
                Some(path) if path.exists() => path,
                _ => return Ok(Self::default()),
            },
        };
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("cannot read config file {}", path.display()))?;
        Self::from_toml(&text).with_context(|| format!("in config file {}", path.display()))
    }
}

/// The default location of the config file
/// (`~/.config/alix/config.toml` on Linux).
pub fn default_config_path() -> Option<PathBuf> {
    directories::ProjectDirs::from("", "", "alix").map(|dirs| dirs.config_dir().join("config.toml"))
}

/// The default decks directory (`~/decks`).
pub fn default_decks_dir() -> Option<PathBuf> {
    directories::BaseDirs::new().map(|dirs| dirs.home_dir().join("decks"))
}

/// Expands a leading `~` to the home directory.
fn expand_tilde(path: &str) -> PathBuf {
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(dirs) = directories::BaseDirs::new()
    {
        return dirs.home_dir().join(rest);
    }
    PathBuf::from(path)
}

/// Retention is clamped to a sane FSRS band — outside it the schedule degenerates.
const MIN_RETENTION: f64 = 0.70;
const MAX_RETENTION: f64 = 0.99;

/// Parses a `retire_after` value: `"never"` → `None` (retirement disabled), or
/// `<n><unit>` with unit `d`/`w`/`m`/`y` (days/weeks/months/years; a bare number is
/// days) → `Some(days)`. Weeks ×7, months ×30, years ×365.
fn parse_retire_after(s: &str) -> Result<Option<u32>> {
    let s = s.trim();
    if s.eq_ignore_ascii_case("never") {
        return Ok(None);
    }
    let split = s.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(s.len());
    let (num, unit) = s.split_at(split);
    let Ok(n) = num.trim().parse::<u32>() else {
        bail!("invalid retire_after {s:?}: expected e.g. \"1y\", \"2w\", \"30d\", or \"never\"");
    };
    let days = match unit.trim().to_ascii_lowercase().as_str() {
        "" | "d" => n,
        "w" => n.saturating_mul(7),
        "m" => n.saturating_mul(30),
        "y" => n.saturating_mul(365),
        other => {
            bail!("invalid retire_after unit {other:?}: expected d, w, m, or y (or \"never\")")
        }
    };
    Ok(Some(days))
}

/// Parses an `acquire_cooldown` value: `<n><unit>` with unit `s`/`m`/`h`
/// (seconds/minutes/hours; a bare number is minutes) → milliseconds. `"0"`
/// disables the cooldown (and with it the same-card re-serve floor).
fn parse_acquire_cooldown(s: &str) -> Result<u64> {
    let s = s.trim();
    let split = s.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(s.len());
    let (num, unit) = s.split_at(split);
    let Ok(n) = num.trim().parse::<u64>() else {
        bail!("invalid acquire_cooldown {s:?}: expected e.g. \"90s\", \"5m\", or \"1h\"");
    };
    let ms = match unit.trim().to_ascii_lowercase().as_str() {
        "s" => n.saturating_mul(1000),
        "" | "m" => n.saturating_mul(60 * 1000),
        "h" => n.saturating_mul(60 * 60 * 1000),
        other => {
            bail!("invalid acquire_cooldown unit {other:?}: expected s, m, or h")
        }
    };
    Ok(ms)
}

/// Parses a `deadline_ramp` value: `<n><unit>` with unit `d`/`w` (a bare
/// number is days) → days. `0` disables the retention ramp (cap only).
fn parse_ramp_days(s: &str) -> Result<u32> {
    let s = s.trim();
    let split = s.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(s.len());
    let (num, unit) = s.split_at(split);
    let Ok(n) = num.trim().parse::<u32>() else {
        bail!("invalid deadline_ramp {s:?}: expected e.g. \"14d\", \"2w\", or \"0\"");
    };
    match unit.trim().to_ascii_lowercase().as_str() {
        "" | "d" => Ok(n),
        "w" => Ok(n.saturating_mul(7)),
        other => bail!("invalid deadline_ramp unit {other:?}: expected d or w"),
    }
}

/// Lint for malformed deadline keys in a workspace's `alix.local.toml`.
/// Returns a vector of human-readable complaints (empty when the file is absent,
/// unparseable as TOML, or both keys are fine). The rule lives in the lib so the
/// lenient overlay and the lint cannot drift.
pub fn local_review_lint(dir: &Path) -> Vec<String> {
    let path = dir.join(LOCAL_MANIFEST);
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return Vec::new(),
    };
    let raw: RawLocalConfig = match toml::from_str(&text) {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };

    let mut complaints = Vec::new();

    if let Some(date) = &raw.review.deadline
        && let Err(e) = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
    {
        complaints.push(format!(
            "deadline = {date:?}: invalid date (expected YYYY-MM-DD). {e}"
        ));
    }

    if let Some(ramp) = &raw.review.deadline_ramp
        && let Err(e) = parse_ramp_days(ramp)
    {
        complaints.push(format!("deadline_ramp = {ramp:?}: {e}"));
    }

    complaints
}

/// A self-documenting template for `config --init`: every option is shown
/// commented out at its default value, so the emitted file overrides nothing
/// (uncomment a line to change it; defaults you leave commented still track
/// future versions). Section headers stay active so a single line can be
/// uncommented beneath one.
pub fn default_config_toml() -> &'static str {
    r#"# alix configuration.
#
# Every option below is shown commented out at its default value, as a
# reference. Uncomment a line and edit it to override that default; lines you
# leave commented keep the built-in default, so improvements to the defaults
# in newer versions still reach you. Keep the section headers ([keys.review],
# [keys.picker], [keys.browse], [ask], [generate], [exam], [trace], [ai],
# [serve]) so an uncommented line lands in the right section.
#
# Keys are written as a single character ("j"), a special key name
# ("space", "enter", "tab", "esc", "backspace"), or either with a "ctrl-"
# prefix ("ctrl-s"). The first key of each list is shown in the footer.
#
# Note: while you are typing an answer (typing and typeline mode), plain
# character bindings are ignored so they cannot shadow text input; use
# ctrl-/special keys for hint, skip and quit.

# Directory the startup picker lists decks from (when `alix` is launched
# without deck arguments). A leading ~ is expanded. Defaults to ~/decks.
# decks_dir = "~/decks"

# Review key bindings (flip / typing / typeline / choice modes).
[keys.review]
# failed = ["1", "f"]           # self-graded: grade as failed (reset)
# partly = ["2", "p"]           # self-graded: grade as partly (FSRS Hard, still a pass)
# passed = ["3", "n"]           # self-graded: grade as passed (advance)
# reveal = ["space", "enter"]   # flip mode: show the answer
# hint = ["tab", "ctrl-h", "ctrl-backspace"]  # typing mode (fails the card)
# submit = ["enter"]            # typeline mode: submit the current line
# skip = ["ctrl-s"]             # requeue the current card without grading
# remove = ["ctrl-x"]           # mark the card for removal from the deck file
# promote = ["ctrl-p"]          # promote a virtual (remediation) card into its deck file
# continue = ["enter", "space"] # leave the feedback screen
# restart = ["r"]               # start a new session from the summary screen
# ask = ["?"]                   # ask the tutor about an answered card
# make_note = ["ctrl-n"]        # ask view: condense the conversation into a note
# make_card = ["ctrl-d"]        # ask view: distill the conversation into a card
# quit = ["esc", "ctrl-c"]      # quit the session

# Navigation keys for the deck picker (Vim-style by default). The arrow keys,
# Enter (open) and Esc (back) always work regardless of these; jumping to the
# first/last row is fixed at g / G / Home / End (like [keys.browse]).
[keys.picker]
# up = ["k"]                    # move up
# down = ["j"]                  # move down
# open = ["l"]                  # open the focused row
# back = ["h"]                  # step back / cancel
# filter = ["/", "ctrl-f"]      # start filtering
# mastered = ["m"]              # open the Mastered window
# depth = ["v"]                 # open the focused deck's depth menu (Esc closes it too)
# recognize = ["1"]             # with the menu open, start at that depth;
# recall = ["2"]                #   Enter always starts the highlighted
# reconstruct = ["3"]           #   (last-used) one
# cram = ["c"]                  # toggle the menu's cram tick-box (serve not-yet-due cards too)

# Key bindings for the read-only Browse overlay (b in the picker). Jumping to the first
# and last card is fixed to g / G / Home / End, and the arrow keys always
# move next/previous; these three are configurable:
[keys.browse]
# next = ["l", "n", "space"]    # next card
# prev = ["h", "p"]             # previous card
# remove = ["x"]                # mark the card for removal from the deck file
# quit = ["q", "esc", "ctrl-c"] # leave the browser

# Settings for the tutor integration. Questions are sent to the
# command below together with the card as context.
[ask]
# backend = "claude"            # AI CLI backend: claude | gemini | codex | copilot
# command = "claude"            # executable to run
# model = ""                    # --model override; empty = the CLI's default
# effort = ""                   # --effort: low|medium|high|xhigh|max; empty = CLI default
# timeout_secs = 120            # give up waiting after this many seconds
# Permission mode for the headless CLI. "dontAsk" silently denies any tool
# not listed below — no interactive prompt (which would hang -p mode).
# Other values: "bypassPermissions" (allow everything; unsafe), "default"
# (prompts, so it hangs headless). Empty omits the flag.
# permission_mode = "dontAsk"
# Tools the assistant may use. With "dontAsk" this is an exclusive
# allowlist; the defaults let it consult deck links but nothing else.
# allowed_tools = ["WebFetch", "WebSearch"]
# Let the tutor READ the card's source (Read/Glob/Grep at the deck's % source:
# project root) to verify its answer instead of relying on memory. Off by
# default: it grants the (possibly LAN-served) tutor file-read access — only
# enable on a machine and network you trust.
# source_access = false
# Pre-flight size guard: warn and confirm before spending a large model call on
# a local source tree bigger than this many bytes (0 = always proceed silently).
# preflight_threshold = 5000000

# AI deck generation (`alix deck <source>`). Reuses the [ask] command,
# permission mode and tool allowlist (WebFetch reads the page).
[generate]
# model = ""                    # --model override; empty = use [ask] / CLI default
# timeout_secs = 300            # generation is slower than a single question
# max_cards = 30                # upper bound on cards per deck
# extra = ""                    # extra guidance appended to the prompt
# prompt = ""                   # full prompt override; may use {url} and {max_cards}
# review = false                # run a second pass to drop redundant cards (--review)

# AI exam (`alix exam <deck>`). Generates open understanding questions from
# the deck's `% source:` and grades typed answers; passing marks the deck
# "mastered" and unlocks its dependents. Reuses the [ask] command, permission
# mode and tool allowlist (WebFetch reads a source URL).
[exam]
# model = ""                    # --model override; empty = use [ask] / CLI default
# timeout_secs = 300            # each exam call is slower than a single question
# num_questions = 5             # questions asked per sitting
# pass_threshold = 1.0          # fraction of questions that must fully pass (1.0 = all)
# strictness = "balanced"       # answer grading: strict | balanced | lenient
# retry_cooldown_secs = 3600    # wait this long before re-sitting a FAILED trace exam (0 = off)
# extra = ""                    # extra guidance appended to question generation

# Trace building (`alix generate <trace-stub>` / `--trace`). Explores the `% source:`
# to discover the path and writes the checkpoints back. Reuses the [ask] command,
# but runs with read-only file tools (Read/Glob/Grep, + WebFetch for a URL
# source) and the source root as the working directory — never a write/shell tool.
[trace]
# model = ""                    # empty = each backend's strong model (Claude: opus), then [ask] / CLI default
# effort = "high"               # default; --effort: low|medium|high|xhigh|max
# timeout_secs = 600            # exploring a source is the slowest call
# extra = ""                    # extra guidance appended to the build prompt
# auto_grade = false            # AI-grade walk predictions (a model call per hop)

# AI deck augmentation (`alix deck augment <deck>`). Generates choice-mode
# distractors (and notes) into a sidecar cache beside your progress; review
# reads them. Reuses the [ask] command; generation is a tool-free text call.
[ai]
# model = ""                    # --model override; empty = use [ask] / CLI default
# distractor_count = 3          # wrong options generated per choice card
# variant_count = 4             # reworded question variants generated per card
# keypoint_count = 5            # max key points per card (explain-mode checklist)
# timeout_secs = 300            # a whole-deck batch is a big call; wait this long

# The web server bare `alix` starts. Binds to localhost by default; `--lan`
# exposes it to the network and `--port` overrides the port set here.
[serve]
# port = 7777                   # default port (--port overrides per instance)
# audience = "adult"            # or "kids" — which frontend `/` serves, and the tutor's voice

# Review pacing (how the FSRS scheduler paces you). Personal — a workspace can
# override these in its own alix.local.toml (which is never shared).
[review]
# retention = 0.9               # FSRS target retrievability (0.70–0.99); higher = shorter intervals
# retire_after = "1y"           # a card rests once its interval reaches this ("2w", "6m", "30d", or "never")
# acquire_cooldown = "5m"       # settle gap before a new card's first quiz, and the same-card retry floor ("90s", "10m"; "0" = none)
# max_new = 10                  # max never-seen cards a session introduces (--new overrides per instance)
# limit = 40                    # session size cap (--limit overrides; unset = no cap)
"#
}

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

    #[test]
    fn review_defaults_when_unset() {
        let config = Config::from_toml("").unwrap();
        assert_eq!(0.9, config.review.retention);
        assert_eq!(Some(365), config.review.retire_after_days);
        assert_eq!(
            crate::scheduler::DEFAULT_ACQUIRE_COOLDOWN_MS,
            config.review.acquire_cooldown_ms
        );
    }

    #[test]
    fn review_parses_acquire_cooldown_units() {
        let load = |v: &str| {
            Config::from_toml(&format!("[review]\nacquire_cooldown = \"{v}\"\n"))
                .unwrap()
                .review
                .acquire_cooldown_ms
        };
        assert_eq!(90_000, load("90s"));
        assert_eq!(600_000, load("10m"));
        assert_eq!(3_600_000, load("1h"));
        assert_eq!(120_000, load("2"), "a bare number is minutes");
        assert_eq!(0, load("0"), "zero disables the cooldown");
    }

    #[test]
    fn review_rejects_a_malformed_acquire_cooldown() {
        assert!(Config::from_toml("[review]\nacquire_cooldown = \"soon\"\n").is_err());
        assert!(Config::from_toml("[review]\nacquire_cooldown = \"5x\"\n").is_err());
    }

    #[test]
    fn review_parses_retention_and_retire_after() {
        let config =
            Config::from_toml("[review]\nretention = 0.95\nretire_after = \"2w\"\n").unwrap();
        assert_eq!(0.95, config.review.retention);
        assert_eq!(Some(14), config.review.retire_after_days);
    }

    #[test]
    fn review_retire_after_never_disables_retirement() {
        let config = Config::from_toml("[review]\nretire_after = \"never\"\n").unwrap();
        assert_eq!(None, config.review.retire_after_days);
    }

    #[test]
    fn review_retention_is_clamped_to_a_sane_band() {
        let config = Config::from_toml("[review]\nretention = 0.5\n").unwrap();
        assert_eq!(MIN_RETENTION, config.review.retention);
    }

    #[test]
    fn review_rejects_a_malformed_retire_after() {
        assert!(Config::from_toml("[review]\nretire_after = \"soon\"\n").is_err());
    }

    #[test]
    fn for_workspace_overlays_local_overrides() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\nretention = 0.85\nretire_after = \"never\"\n",
        )
        .unwrap();
        let resolved = ReviewConfig::default().for_workspace(dir.path());
        assert_eq!(0.85, resolved.retention);
        assert_eq!(None, resolved.retire_after_days);
    }

    #[test]
    fn for_workspace_overlays_the_acquire_cooldown() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\nacquire_cooldown = \"90s\"\n",
        )
        .unwrap();
        let resolved = ReviewConfig::default().for_workspace(dir.path());
        assert_eq!(90_000, resolved.acquire_cooldown_ms);
        // Other keys keep their base values.
        assert_eq!(0.9, resolved.retention);
    }

    #[test]
    fn for_workspace_keeps_base_for_unset_keys() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\nretention = 0.85\n",
        )
        .unwrap();
        let base = ReviewConfig {
            retention: 0.9,
            retire_after_days: Some(30),
            ..Default::default()
        };
        let resolved = base.for_workspace(dir.path());
        assert_eq!(0.85, resolved.retention);
        assert_eq!(Some(30), resolved.retire_after_days); // unset key → base kept
    }

    #[test]
    fn review_pacing_keys_parse_and_default_to_unset() {
        let config = Config::from_toml("[review]\nmax_new = 5\nlimit = 40\n").unwrap();
        assert_eq!(Some(5), config.review.max_new);
        assert_eq!(Some(40), config.review.limit);
        // Absent keys stay unset — the launcher falls back to its built-ins.
        let bare = Config::from_toml("").unwrap();
        assert_eq!(None, bare.review.max_new);
        assert_eq!(None, bare.review.limit);
    }

    #[test]
    fn a_review_depth_key_is_now_rejected() {
        // deny_unknown_fields: the removed dial errors loudly, not silently (pre-1.0 break).
        assert!(Config::from_toml("[review]\ndepth = 2\n").is_err());
    }

    #[test]
    fn for_workspace_ignores_a_missing_or_malformed_file() {
        let dir = tempfile::tempdir().unwrap();
        let base = ReviewConfig::default();
        assert_eq!(base, base.for_workspace(dir.path())); // missing → unchanged
        std::fs::write(dir.path().join("alix.local.toml"), "this is = = not toml\n").unwrap();
        assert_eq!(base, base.for_workspace(dir.path())); // malformed → unchanged
    }

    #[test]
    fn review_deadline_defaults_to_none_and_ramp_to_14() {
        let review = ReviewConfig::default();
        assert_eq!(None, review.deadline);
        assert_eq!(14, review.deadline_ramp_days);
    }

    #[test]
    fn for_workspace_overlays_deadline_and_ramp() {
        let dir = tempfile::tempdir().unwrap();
        // The deadline overlay only fires inside a real workspace (manifest + a deck).
        std::fs::write(dir.path().join("alix.toml"), "title = \"W\"\n").unwrap();
        std::fs::write(dir.path().join("a.txt"), "# q\n\ta\n").unwrap();
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\ndeadline = \"2026-09-01\"\ndeadline_ramp = \"3w\"\n",
        )
        .unwrap();
        let resolved = ReviewConfig::default().for_workspace(dir.path());
        assert_eq!(
            Some(chrono::NaiveDate::from_ymd_opt(2026, 9, 1).unwrap()),
            resolved.deadline
        );
        assert_eq!(21, resolved.deadline_ramp_days);
    }

    #[test]
    fn for_workspace_ignores_a_malformed_deadline_but_keeps_other_keys() {
        // The overlay is lenient key-by-key: a bad date must not eat the file. A real
        // workspace fixture (manifest + a deck) keeps this test about leniency, not
        // about the workspace gate (covered separately).
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("alix.toml"), "title = \"W\"\n").unwrap();
        std::fs::write(dir.path().join("a.txt"), "# q\n\ta\n").unwrap();
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\ndeadline = \"soonish\"\nretention = 0.85\n",
        )
        .unwrap();
        let resolved = ReviewConfig::default().for_workspace(dir.path());
        assert_eq!(None, resolved.deadline);
        assert_eq!(0.85, resolved.retention);
    }

    #[test]
    fn a_plain_folder_gets_no_deadline_overlay() {
        // DECISION 2026-07-15: deadline/deadline_ramp apply only inside a real
        // workspace (manifest present). A bare decks folder has no chip, no web
        // action, and no doctor lint for a deadline — applying it there would
        // silently ramp retention with nothing to explain why. Pacing keys
        // (retention, retire_after, acquire_cooldown, max_new, limit) have no such
        // product surface gap, so they keep working in plain folders as before.
        let dir = tempfile::tempdir().unwrap();
        // Deliberately no alix.toml manifest: a bare tempdir is not a workspace.
        std::fs::write(
            dir.path().join("alix.local.toml"),
            "[review]\ndeadline = \"2026-09-01\"\nretention = 0.85\n",
        )
        .unwrap();
        let resolved = ReviewConfig::default().for_workspace(dir.path());
        assert_eq!(None, resolved.deadline, "a plain folder's deadline is dead");
        assert_eq!(0.85, resolved.retention, "pacing keys stay folder-friendly");
    }

    #[test]
    fn ramp_days_parse_units_and_zero() {
        assert_eq!(14, parse_ramp_days("14d").unwrap());
        assert_eq!(21, parse_ramp_days("3w").unwrap());
        assert_eq!(10, parse_ramp_days("10").unwrap(), "bare number is days");
        assert_eq!(0, parse_ramp_days("0").unwrap(), "0 = cap only, no ramp");
        assert!(parse_ramp_days("soon").is_err());
        assert!(parse_ramp_days("5m").is_err(), "months are not a ramp unit");
    }

    #[test]
    fn the_global_config_rejects_deadline_keys() {
        // A deadline is a per-workspace concept; the global [review] table
        // must refuse it loudly (serde deny_unknown_fields).
        assert!(Config::from_toml("[review]\ndeadline = \"2026-09-01\"\n").is_err());
        assert!(Config::from_toml("[review]\ndeadline_ramp = \"14d\"\n").is_err());
    }

    #[test]
    fn parse_retire_after_units() {
        assert_eq!(Some(365), parse_retire_after("1y").unwrap());
        assert_eq!(Some(180), parse_retire_after("6m").unwrap());
        assert_eq!(Some(14), parse_retire_after("2w").unwrap());
        assert_eq!(Some(30), parse_retire_after("30d").unwrap());
        assert_eq!(Some(45), parse_retire_after("45").unwrap());
        assert_eq!(None, parse_retire_after("never").unwrap());
        assert!(parse_retire_after("").is_err());
        assert!(parse_retire_after("1x").is_err());
    }

    #[test]
    fn parse_single_chars() {
        assert_eq!(
            KeyPattern {
                key: Key::Char('j'),
                ctrl: false
            },
            parse_key("j").unwrap()
        );
        assert_eq!(
            KeyPattern {
                key: Key::Char('1'),
                ctrl: false
            },
            parse_key("1").unwrap()
        );
    }

    #[test]
    fn parse_special_keys() {
        assert_eq!(Key::Char(' '), parse_key("space").unwrap().key);
        assert_eq!(Key::Enter, parse_key("enter").unwrap().key);
        assert_eq!(Key::Enter, parse_key("return").unwrap().key);
        assert_eq!(Key::Tab, parse_key("tab").unwrap().key);
        assert_eq!(Key::Esc, parse_key("ESC").unwrap().key);
        assert_eq!(Key::Backspace, parse_key("backspace").unwrap().key);
    }

    #[test]
    fn parse_ctrl_combinations() {
        assert_eq!(
            KeyPattern {
                key: Key::Char('s'),
                ctrl: true
            },
            parse_key("ctrl-s").unwrap()
        );
        assert_eq!(
            KeyPattern {
                key: Key::Backspace,
                ctrl: true
            },
            parse_key("ctrl-backspace").unwrap()
        );
    }

    #[test]
    fn parse_rejects_garbage() {
        assert!(parse_key("jj").is_err());
        assert!(parse_key("").is_err());
        assert!(parse_key("ctrl-").is_err());
        assert!(parse_key("super-x").is_err());
    }

    #[test]
    fn display_labels() {
        assert_eq!("j", parse_key("j").unwrap().to_string());
        assert_eq!("SPACE", parse_key("space").unwrap().to_string());
        assert_eq!("Ctrl-S", parse_key("ctrl-s").unwrap().to_string().as_str());
        assert_eq!("ESC", parse_key("esc").unwrap().to_string());
    }

    #[test]
    fn defaults_are_consistent_and_an_empty_file_loads() {
        // Hermetic: never reads the user's real config dir (`Config::load(None)`
        // would). Defaults must be self-consistent, and a present-but-empty config
        // file loads as all-defaults.
        assert_eq!(Bindings::default(), Config::default().keys);
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("config.toml");
        std::fs::write(&cfg, "").unwrap();
        assert!(Config::load(Some(&cfg)).is_ok());
    }

    #[test]
    fn rebind_grades_to_jkl() {
        let config = Config::from_toml(
            "[keys.review]\nfailed = [\"j\"]\npartly = [\"k\"]\npassed = [\"l\"]\n",
        )
        .unwrap();
        assert_eq!(vec![parse_key("j").unwrap()], config.keys.failed);
        assert_eq!(vec![parse_key("k").unwrap()], config.keys.partly);
        assert_eq!(vec![parse_key("l").unwrap()], config.keys.passed);
        // Unmentioned actions keep their defaults.
        assert_eq!(Bindings::default().quit, config.keys.quit);
    }

    #[test]
    fn continue_is_a_valid_table_key() {
        let config = Config::from_toml("[keys.review]\ncontinue = [\"ctrl-n\"]\n").unwrap();
        assert_eq!(vec![parse_key("ctrl-n").unwrap()], config.keys.cont);
    }

    #[test]
    fn review_nav_keys_default_to_k_j_and_can_be_rebound() {
        // The MC-choice / key-point up-and-down nav defaults to Vim k (up) and
        // j (down), and is rebindable under [keys.review] like any other action.
        assert_eq!(vec![parse_key("k").unwrap()], Bindings::default().up);
        assert_eq!(vec![parse_key("j").unwrap()], Bindings::default().down);
        let config = Config::from_toml("[keys.review]\nup = [\"w\"]\ndown = [\"s\"]\n").unwrap();
        assert_eq!(vec![parse_key("w").unwrap()], config.keys.up);
        assert_eq!(vec![parse_key("s").unwrap()], config.keys.down);
    }

    #[test]
    fn tutor_distill_keys_default_and_can_be_rebound() {
        // Make this a note (ctrl-n) and Make this a card (ctrl-d) are both
        // rebindable [keys.review] actions like any other.
        assert_eq!(
            vec![parse_key("ctrl-n").unwrap()],
            Bindings::default().make_note
        );
        assert_eq!(
            vec![parse_key("ctrl-d").unwrap()],
            Bindings::default().make_card
        );
        let config = Config::from_toml(
            "[keys.review]\nmake_note = [\"ctrl-y\"]\nmake_card = [\"ctrl-u\"]\n",
        )
        .unwrap();
        assert_eq!(vec![parse_key("ctrl-y").unwrap()], config.keys.make_note);
        assert_eq!(vec![parse_key("ctrl-u").unwrap()], config.keys.make_card);
    }

    #[test]
    fn picker_keys_override_and_default() {
        let config = Config::from_toml("[keys.picker]\ndown = [\"n\"]\nopen = [\"o\"]\n").unwrap();
        assert_eq!(vec![parse_key("n").unwrap()], config.picker.down);
        assert_eq!(vec![parse_key("o").unwrap()], config.picker.open);
        // Unmentioned picker keys keep their Vim defaults.
        assert_eq!(PickerKeys::default().up, config.picker.up);
        assert_eq!(PickerKeys::default().mastered, config.picker.mastered);
    }

    #[test]
    fn depth_menu_keys_override_and_default() {
        let config =
            Config::from_toml("[keys.picker]\ndepth = [\"s\"]\nreconstruct = [\"3\", \"e\"]\n")
                .unwrap();
        assert_eq!(vec![parse_key("s").unwrap()], config.picker.depth);
        assert_eq!(
            vec![parse_key("3").unwrap(), parse_key("e").unwrap()],
            config.picker.reconstruct
        );
        // Unmentioned depth keys keep their digit defaults.
        assert_eq!(vec![parse_key("1").unwrap()], config.picker.recognize);
        assert_eq!(vec![parse_key("2").unwrap()], config.picker.recall);
    }

    #[test]
    fn unknown_action_is_rejected() {
        assert!(Config::from_toml("[keys.review]\nfrobnicate = [\"x\"]\n").is_err());
    }

    #[test]
    fn unknown_section_is_rejected() {
        assert!(Config::from_toml("[keyz]\nagain = [\"x\"]\n").is_err());
    }

    #[test]
    fn pre_nesting_key_sections_are_rejected() {
        // The old top-level [picker]/[browse] tables moved under [keys]; the old
        // spelling now errors loudly (no compat shim, pre-1.0), pointing the user
        // at the rename.
        assert!(Config::from_toml("[picker]\ndown = [\"n\"]\n").is_err());
        assert!(Config::from_toml("[browse]\nnext = [\"n\"]\n").is_err());
    }

    #[test]
    fn bad_key_in_binding_is_rejected() {
        let err = Config::from_toml("[keys.review]\nfailed = [\"jj\"]\n").unwrap_err();
        assert!(format!("{err:#}").contains("failed"));
    }

    #[test]
    fn template_parses_to_defaults() {
        // As written (all settings commented out), the template overrides
        // nothing.
        let config = Config::from_toml(default_config_toml()).unwrap();
        assert_eq!(Config::default(), config);
    }

    #[test]
    fn template_commented_values_equal_defaults() {
        // Uncomment every `# key = ...` setting line and confirm the result is
        // still exactly the defaults — so the documented example values are
        // correct and valid TOML, not just inert (possibly rotted) comments.
        // `decks_dir` is excluded: its example "~/decks" is the *effective*
        // default but the struct default is `None` ("use ~/decks").
        let uncommented = default_config_toml()
            .lines()
            .map(|line| match line.trim_start().strip_prefix("# ") {
                Some(rest) if is_setting_line(rest) => rest,
                _ => line,
            })
            .collect::<Vec<_>>()
            .join("\n");
        let config = Config::from_toml(&uncommented).unwrap();
        assert_eq!(Config::default(), config);
    }

    /// `true` if `s` looks like a `key = ...` assignment for a rebindable
    /// setting (lower-case/underscore key) — except the keys whose template
    /// value is the *effective* default while the struct default is `None`
    /// ("unset, resolved elsewhere"): `decks_dir` (~/decks), `max_new` (the
    /// launcher's 10), and `limit` (an example; unset = no cap).
    fn is_setting_line(s: &str) -> bool {
        let Some((key, _)) = s.split_once('=') else {
            return false;
        };
        let key = key.trim();
        !key.is_empty()
            && !matches!(key, "decks_dir" | "max_new" | "limit")
            && key.chars().all(|c| c.is_ascii_lowercase() || c == '_')
    }

    #[test]
    fn ask_section_overrides_defaults() {
        let config = Config::from_toml(
            "[ask]\ncommand = \"my-claude\"\nmodel = \"haiku\"\ntimeout_secs = 30\n",
        )
        .unwrap();
        assert_eq!("my-claude", config.ask.command);
        assert_eq!(Some("haiku".to_string()), config.ask.model);
        assert_eq!(30, config.ask.timeout_secs);
        // Unmentioned fields keep their safe defaults.
        assert_eq!("dontAsk", config.ask.permission_mode);
        assert_eq!(vec!["WebFetch", "WebSearch"], config.ask.allowed_tools);
    }

    #[test]
    fn trace_defaults_to_high_effort_and_backend_chosen_model() {
        // Trace still breaks the inherit-the-CLI-default pattern on effort
        // (correctness-critical, fails silently), but the *model* is now left
        // unset here so each backend picks its own strong model
        // (`Backend::default_trace_model`); the effective model is resolved in
        // `trace_ai::build_run_config`.
        let trace = Config::default().trace;
        assert_eq!(None, trace.model);
        assert_eq!(Some("high".to_string()), trace.effort);
    }

    #[test]
    fn trace_section_overrides_model_and_effort() {
        let config = Config::from_toml("[trace]\nmodel = \"sonnet\"\neffort = \"max\"\n").unwrap();
        assert_eq!(Some("sonnet".to_string()), config.trace.model);
        assert_eq!(Some("max".to_string()), config.trace.effort);
    }

    #[test]
    fn ask_effort_is_off_by_default_and_overridable() {
        assert_eq!(None, Config::default().ask.effort);
        let config = Config::from_toml("[ask]\neffort = \"medium\"\n").unwrap();
        assert_eq!(Some("medium".to_string()), config.ask.effort);
    }

    #[test]
    fn ai_defaults_to_three_distractors_and_cli_model() {
        let ai = Config::default().ai;
        assert_eq!(3, ai.distractor_count);
        assert_eq!(None, ai.model);
    }

    #[test]
    fn ai_section_overrides_defaults() {
        let config = Config::from_toml("[ai]\ndistractor_count = 5\nmodel = \"haiku\"\n").unwrap();
        assert_eq!(5, config.ai.distractor_count);
        assert_eq!(Some("haiku".to_string()), config.ai.model);
    }

    #[test]
    fn ai_empty_model_means_cli_default() {
        let config = Config::from_toml("[ai]\nmodel = \"\"\n").unwrap();
        assert_eq!(None, config.ai.model);
    }

    #[test]
    fn unknown_ai_setting_is_rejected() {
        assert!(Config::from_toml("[ai]\nbogus = 1\n").is_err());
    }

    #[test]
    fn serve_audience_defaults_to_adult_and_parses_kids() {
        let def = Config::default();
        assert_eq!(def.serve.audience, Audience::Adult);
        let c = Config::from_toml("[serve]\naudience = \"kids\"\n").unwrap();
        assert_eq!(c.serve.audience, Audience::Kids);
    }

    #[test]
    fn decks_dir_defaults_to_none_and_expands_tilde() {
        assert_eq!(None, Config::default().decks_dir);
        let config = Config::from_toml("decks_dir = \"~/my-decks\"\n").unwrap();
        let dir = config.decks_dir.unwrap();
        assert!(dir.ends_with("my-decks"));
        assert!(!dir.to_string_lossy().contains('~'));
    }

    #[test]
    fn ask_permission_and_tools_are_configurable() {
        let config = Config::from_toml(
            "[ask]\npermission_mode = \"bypassPermissions\"\n\
             allowed_tools = [\"WebFetch\", \"Read\"]\n",
        )
        .unwrap();
        assert_eq!("bypassPermissions", config.ask.permission_mode);
        assert_eq!(vec!["WebFetch", "Read"], config.ask.allowed_tools);
    }

    #[test]
    fn empty_model_means_cli_default() {
        let config = Config::from_toml("[ask]\nmodel = \"\"\n").unwrap();
        assert_eq!(None, config.ask.model);
    }

    #[test]
    fn unknown_ask_setting_is_rejected() {
        assert!(Config::from_toml("[ask]\ntemperature = 1.0\n").is_err());
    }

    #[test]
    fn exam_strictness_defaults_to_balanced_and_parses() {
        assert_eq!(Strictness::Balanced, Config::default().exam.strictness);
        let config = Config::from_toml("[exam]\nstrictness = \"strict\"\n").unwrap();
        assert_eq!(Strictness::Strict, config.exam.strictness);
        // Case-insensitive, and other [exam] fields keep their defaults.
        let config = Config::from_toml("[exam]\nstrictness = \"LENIENT\"\n").unwrap();
        assert_eq!(Strictness::Lenient, config.exam.strictness);
        assert_eq!(5, config.exam.num_questions);
    }

    #[test]
    fn invalid_exam_strictness_is_rejected() {
        let err = Config::from_toml("[exam]\nstrictness = \"harsh\"\n").unwrap_err();
        assert!(format!("{err:#}").contains("strictness"));
    }

    #[test]
    fn browse_keys_default_to_vim_and_are_rebindable() {
        // Defaults: l/n/space next, h/p prev.
        let defaults = BrowseBindings::default();
        assert_eq!(parse_key("l").unwrap(), defaults.next[0]);
        assert_eq!(parse_key("h").unwrap(), defaults.prev[0]);

        let config = Config::from_toml("[keys.browse]\nnext = [\"j\"]\nprev = [\"k\"]\n").unwrap();
        assert_eq!(vec![parse_key("j").unwrap()], config.browse.next);
        assert_eq!(vec![parse_key("k").unwrap()], config.browse.prev);
        // Unmentioned browse actions keep their defaults.
        assert_eq!(defaults.quit, config.browse.quit);
    }

    #[test]
    fn unknown_browse_setting_is_rejected() {
        assert!(Config::from_toml("[keys.browse]\nfirst = [\"g\"]\n").is_err());
    }

    #[test]
    fn backend_defaults_to_claude() {
        assert_eq!(BackendKind::Claude, Config::default().ask.backend);
        // An empty config file also yields the default.
        let config = Config::from_toml("").unwrap();
        assert_eq!(BackendKind::Claude, config.ask.backend);
    }

    #[test]
    fn backend_gemini_parses() {
        let config = Config::from_toml("[ask]\nbackend = \"gemini\"\n").unwrap();
        assert_eq!(BackendKind::Gemini, config.ask.backend);
        // Other [ask] fields keep their defaults.
        assert_eq!("claude", config.ask.command);
    }

    #[test]
    fn backend_parsing_is_case_insensitive() {
        let config = Config::from_toml("[ask]\nbackend = \"Claude\"\n").unwrap();
        assert_eq!(BackendKind::Claude, config.ask.backend);
        let config = Config::from_toml("[ask]\nbackend = \"CODEX\"\n").unwrap();
        assert_eq!(BackendKind::Codex, config.ask.backend);
        let config = Config::from_toml("[ask]\nbackend = \"Copilot\"\n").unwrap();
        assert_eq!(BackendKind::Copilot, config.ask.backend);
    }

    #[test]
    fn unknown_backend_is_rejected() {
        let err = Config::from_toml("[ask]\nbackend = \"grok\"\n").unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("backend"),
            "error should mention 'backend': {msg}"
        );
    }

    #[test]
    fn local_review_lint_flags_malformed_deadline_keys() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(LOCAL_MANIFEST),
            "[review]\ndeadline = \"soonish\"\ndeadline_ramp = \"5m\"\n",
        )
        .unwrap();
        let complaints = local_review_lint(dir.path());
        assert_eq!(2, complaints.len());
        assert!(complaints[0].contains("deadline"));

        std::fs::write(
            dir.path().join(LOCAL_MANIFEST),
            "[review]\ndeadline = \"2026-09-01\"\n",
        )
        .unwrap();
        assert!(local_review_lint(dir.path()).is_empty());
        let empty = tempfile::tempdir().unwrap();
        assert!(local_review_lint(empty.path()).is_empty());
    }
}

#[cfg(all(test, feature = "full"))]
mod clap_parity {
    use clap::ValueEnum;

    use super::*;

    /// The hand-written `parse` and the clap value names must agree on every
    /// variant, or a `%` directive would parse differently from the CLI flag.
    #[test]
    fn parse_matches_the_clap_value_names() {
        for variant in Strictness::value_variants() {
            let name = variant.to_possible_value().expect("a value name");
            assert_eq!(
                Some(*variant),
                Strictness::parse(name.get_name()),
                "{name:?}"
            );
        }
        assert_eq!(None, Strictness::parse("no-such-value"));
    }
}