alix 0.2.0

Your personal AI tutor — built for understanding, not just remembering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
//! 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 footer of the TUI. 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 fuzzy 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 clap::ValueEnum;
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 (reset to stage 1).
    pub failed: Vec<KeyPattern>,
    /// Self-graded modes: grade as partly (demote one stage).
    pub partly: Vec<KeyPattern>,
    /// Self-graded modes: grade as passed (advance one stage).
    pub passed: Vec<KeyPattern>,
    /// Flip mode: reveal the answer.
    pub reveal: Vec<KeyPattern>,
    /// Typing mode: reveal a hint (fails the card).
    pub hint: Vec<KeyPattern>,
    /// Fuzzy 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>,
    /// 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 and save it as a card note.
    pub save_note: 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"]),
            reveal: keys(&["space", "enter"]),
            hint: keys(&["tab", "ctrl-h", "ctrl-backspace"]),
            submit: keys(&["enter"]),
            skip: keys(&["ctrl-s"]),
            remove: keys(&["ctrl-x"]),
            cont: keys(&["enter", "space"]),
            restart: keys(&["r"]),
            ask: keys(&["?"]),
            save_note: keys(&["ctrl-n"]),
            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 `[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 `[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>,
}

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"]),
        }
    }
}

/// Key bindings for the read-only browser (`alix browse`), configured in the
/// `[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"]),
        }
    }
}

/// Settings for the ask-Claude integration (`[ask]` in the config file).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AskConfig {
    /// 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 serve --lan`).
    pub source_access: bool,
}

impl Default for AskConfig {
    fn default() -> Self {
        Self {
            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,
        }
    }
}

/// 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, 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,
}

/// 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 (`alix trace --build`, 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`. Defaults to `"opus"` — trace building is an
    /// agentic, correctness-critical, one-shot call where quality dominates, so
    /// it breaks the inherit-the-CLI-default pattern the other AI features use.
    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>,
}

impl Default for TraceConfig {
    fn default() -> Self {
        Self {
            // Building runs one-shot and amortized over many reviews, and a weak
            // model fails silently (a parseable but loose chain), so trace alone
            // defaults to a strong model + high effort.
            model: Some("opus".to_string()),
            effort: Some("high".to_string()),
            timeout_secs: 600,
            extra: None,
        }
    }
}

/// 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,
        }
    }
}

/// Settings for the local web frontend (`alix serve`, the `[serve]` section).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServeConfig {
    /// Default port to listen on (overridden by `--port`).
    pub port: u16,
}

impl Default for ServeConfig {
    fn default() -> Self {
        Self { port: 7777 }
    }
}

/// The whole user configuration.
// Not `Eq`: `ExamConfig::pass_threshold` is an `f64`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Config {
    pub keys: Bindings,
    /// Navigation keys for the deck picker.
    pub picker: PickerKeys,
    /// Key bindings for `alix browse`.
    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,
    /// 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)]
    picker: RawPicker,
    #[serde(default)]
    browse: RawBrowse,
    #[serde(default)]
    ask: RawAsk,
    #[serde(default)]
    generate: RawGenerate,
    #[serde(default)]
    exam: RawExam,
    #[serde(default)]
    trace: RawTrace,
    #[serde(default)]
    ai: RawAi,
    #[serde(default)]
    serve: RawServe,
    decks_dir: Option<String>,
}

#[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>,
}

#[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>,
}

#[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>>,
}

#[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 {
    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>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct RawKeys {
    failed: Option<Vec<String>>,
    partly: Option<Vec<String>>,
    passed: Option<Vec<String>>,
    reveal: Option<Vec<String>>,
    hint: Option<Vec<String>>,
    submit: Option<Vec<String>>,
    skip: Option<Vec<String>>,
    remove: Option<Vec<String>>,
    r#continue: Option<Vec<String>>,
    restart: Option<Vec<String>>,
    ask: Option<Vec<String>>,
    save_note: 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(())
        };

        assign(&mut keys.failed, raw.keys.failed, "failed")?;
        assign(&mut keys.partly, raw.keys.partly, "partly")?;
        assign(&mut keys.passed, raw.keys.passed, "passed")?;
        assign(&mut keys.reveal, raw.keys.reveal, "reveal")?;
        assign(&mut keys.hint, raw.keys.hint, "hint")?;
        assign(&mut keys.submit, raw.keys.submit, "submit")?;
        assign(&mut keys.skip, raw.keys.skip, "skip")?;
        assign(&mut keys.remove, raw.keys.remove, "remove")?;
        assign(&mut keys.cont, raw.keys.r#continue, "continue")?;
        assign(&mut keys.restart, raw.keys.restart, "restart")?;
        assign(&mut keys.ask, raw.keys.ask, "ask")?;
        assign(&mut keys.save_note, raw.keys.save_note, "save_note")?;
        assign(&mut keys.quit, raw.keys.quit, "quit")?;

        let mut picker = PickerKeys::default();
        assign(&mut picker.up, raw.picker.up, "picker.up")?;
        assign(&mut picker.down, raw.picker.down, "picker.down")?;
        assign(&mut picker.open, raw.picker.open, "picker.open")?;
        assign(&mut picker.back, raw.picker.back, "picker.back")?;
        assign(&mut picker.filter, raw.picker.filter, "picker.filter")?;
        assign(&mut picker.mastered, raw.picker.mastered, "picker.mastered")?;

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

        let mut ask = AskConfig::default();
        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;
        }

        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::from_str(s.trim(), true) {
                Ok(v) => exam.strictness = v,
                Err(_) => {
                    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());

        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;
        }

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

        Ok(Self {
            keys,
            picker,
            browse,
            ask,
            generate,
            exam,
            trace,
            ai,
            serve,
            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)
}

/// 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], [picker],
# [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 fuzzy 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 / fuzzy / choice modes).
[keys]
# failed = ["1", "f"]           # self-graded: grade as failed (reset)
# partly = ["2", "p"]           # self-graded: grade as partly (demote one stage)
# 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"]            # fuzzy 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
# continue = ["enter", "space"] # leave the feedback screen
# restart = ["r"]               # start a new session from the summary screen
# ask = ["?"]                   # ask Claude about an answered card
# save_note = ["ctrl-n"]        # ask view: save a condensed note to the deck
# 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 [browse]).
[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

# Key bindings for `alix browse` (the read-only reader). 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:
[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 ask-Claude integration. Questions are sent to the
# command below (the Claude Code CLI) together with the card as context.
[ask]
# 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

# 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 trace --build <deck>`). Explores the deck's `% 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 = "opus"                # default (correctness-critical); empty = use [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

# 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

# Local web frontend (`alix serve`). Binds to localhost by default; `--lan`
# exposes it to the network and `--port` overrides the port set here.
[serve]
# port = 7777                   # default port for `alix serve`
"#
}

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

    #[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]\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]\ncontinue = [\"ctrl-n\"]\n").unwrap();
        assert_eq!(vec![parse_key("ctrl-n").unwrap()], config.keys.cont);
    }

    #[test]
    fn picker_keys_override_and_default() {
        let config = Config::from_toml("[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 unknown_action_is_rejected() {
        assert!(Config::from_toml("[keys]\nfrobnicate = [\"x\"]\n").is_err());
    }

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

    #[test]
    fn bad_key_in_binding_is_rejected() {
        let err = Config::from_toml("[keys]\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), other than `decks_dir`.
    fn is_setting_line(s: &str) -> bool {
        let Some((key, _)) = s.split_once('=') else {
            return false;
        };
        let key = key.trim();
        !key.is_empty()
            && key != "decks_dir"
            && 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_a_strong_model_and_high_effort() {
        // The one AI feature that breaks the inherit-the-CLI-default pattern:
        // trace building is correctness-critical and fails silently.
        let trace = Config::default().trace;
        assert_eq!(Some("opus".to_string()), 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 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("[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("[browse]\nfirst = [\"g\"]\n").is_err());
    }
}