alix 0.1.0

Your personal AI tutor — built for understanding, not just remembering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Parser for the plain-text deck format.
//!
//! The format, line by line (each line is trimmed first, empty lines are
//! skipped):
//!
//! - `# <text>`  at column 0 starts a new card; the text is the front side. An *indented* `#` is
//!   answer content (code comments, Rust attributes, markdown headers), not a card front.
//! - `#? <text>` at column 0 starts a cloze card; `{{...}}` in its answer lines are holes (see the
//!   [`cloze`](crate::cloze) module).
//! - `% <text>`  is a comment and ignored (any indentation).
//! - `% link: <url>` is still a comment to the card parser, but the URL is collected as a
//!   deck-level reference link (see [`parse_links`]); the ask-Claude view offers these to Claude as
//!   background material.
//! - `! <text>`  is a note attached to the current card (any indentation, after its back). Several
//!   consecutive `!` lines form one multi-line note.
//! - any other line is a back line of the current card.
//! - a leading `\` escapes a markup character (`#`, `%`, `!`) so a back line can start with one;
//!   the backslash is stripped.
//!
//! A card consists of one front line, one or more back lines, and an
//! optional note after the back lines. Malformed files yield errors with
//! line numbers rather than panicking.

use std::{path::PathBuf, sync::Arc};

use clap::ValueEnum;
use thiserror::Error;

use crate::{
    answer::Mode,
    card::{Card, Direction, Frontend},
    cloze,
};

/// Markup indicating the front side of a card.
const MARKUP_FRONT: char = '#';
/// Second markup character turning a front into a cloze card (`#?`).
const MARKUP_CLOZE: char = '?';
/// Markup indicating a comment line.
const MARKUP_COMMENT: char = '%';
/// Markup indicating a note.
const MARKUP_NOTE: char = '!';
/// Escape character in case markup and card data collide.
const MARKUP_ESCAPE: char = '\\';
/// All markup characters that can be escaped.
const MARKUP: [char; 3] = [MARKUP_FRONT, MARKUP_COMMENT, MARKUP_NOTE];

/// A parse error, pointing at the offending line of the deck file.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ParseError {
    #[error("line {0}: answer line appears before any '#' card front")]
    BackBeforeFront(usize),
    #[error("line {0}: note appears before any '#' card front")]
    NoteBeforeFront(usize),
    #[error("line {0}: note must come after the card's answer lines")]
    NoteBeforeBack(usize),
    #[error("line {0}: answer lines are not allowed after a note")]
    BackAfterNote(usize),
    #[error("line {0}: card front without an answer")]
    FrontWithoutBack(usize),
    #[error("line {0}: card front is empty")]
    EmptyFront(usize),
    #[error("line {0}: cloze card ('#?') has no {{{{...}}}} holes in its answer")]
    ClozeWithoutHoles(usize),
    #[error("line {0}: empty cloze hole '{{{{}}}}'")]
    EmptyClozeHole(usize),
    #[error("line {0}: unclosed cloze hole (missing the closing '}}}}')")]
    UnclosedClozeHole(usize),
    #[error("line {0}: nested cloze hole")]
    NestedClozeHole(usize),
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum State {
    /// Nothing parsed yet for the current card.
    Init,
    /// A front line has been parsed.
    Front,
    /// At least one back line has been parsed.
    Back,
    /// At least one note line has been parsed; further `!` lines extend the
    /// note, but no more answer lines may follow.
    Note,
}

struct PartialCard {
    front: String,
    /// Answer lines with their 1-based line numbers in the deck file.
    back: Vec<(usize, String)>,
    note: Option<String>,
    line: usize,
    cloze: bool,
    /// Per-card `% mode:` override, if the card declares one.
    mode: Option<Mode>,
    /// Per-card `% direction:`, if the card declares one.
    direction: Option<Direction>,
    /// Per-card `% img:` (question side), raw value as written.
    image: Option<String>,
    /// Per-card `% img-back:` (answer side), raw value as written.
    image_back: Option<String>,
    /// Per-card `% frontend:`, if the card declares one.
    frontend: Option<Frontend>,
    /// Per-card `% at:` trace locator (a source position), raw value as
    /// written.
    at: Option<String>,
    /// Per-card `% given:` lines (repeatable): a trace checkpoint's named
    /// "givens", in order.
    givens: Vec<String>,
}

impl PartialCard {
    /// Turns the finished partial into one card (plain) or several (cloze).
    fn build(self, subject: &Arc<str>, cards: &mut Vec<Card>) -> Result<(), ParseError> {
        if self.cloze {
            // A cloze card's per-card mode applies to each of its sub-cards.
            for mut card in cloze::expand(
                subject,
                &self.front,
                &self.back,
                self.note.as_deref(),
                self.line,
            )? {
                card.mode = self.mode;
                cards.push(card);
            }
        } else {
            let mut card = Card::plain(
                Arc::clone(subject),
                self.front,
                self.back.into_iter().map(|(_, text)| text).collect(),
                self.note,
                self.line,
            );
            card.mode = self.mode;
            card.direction = self.direction;
            card.image = self.image.map(PathBuf::from);
            card.image_back = self.image_back.map(PathBuf::from);
            card.frontend = self.frontend;
            card.at = self.at;
            card.givens = self.givens;
            cards.push(card);
        }
        Ok(())
    }
}

/// Collects deck-level reference links: comment lines of the form
/// `% link: <url>`. They are invisible to the card parser (every `%` line
/// is), so they do not affect card hashes.
pub fn parse_links(text: &str) -> Vec<String> {
    text.lines()
        .filter_map(|raw| {
            let line = raw.trim();
            let rest = line.strip_prefix(MARKUP_COMMENT)?;
            let url = rest.trim().strip_prefix("link:")?.trim();
            (!url.is_empty()).then(|| url.to_string())
        })
        .collect()
}

/// Collects a deck's prerequisite decks: comment lines `% requires: <deck>`
/// (repeatable). Like links, they are invisible to the card parser. The value
/// is a deck name or path, resolved by the caller.
pub fn parse_requires(text: &str) -> Vec<String> {
    text.lines()
        .filter_map(|raw| {
            let rest = raw.trim().strip_prefix(MARKUP_COMMENT)?;
            let dep = rest.trim().strip_prefix("requires:")?.trim();
            (!dep.is_empty()).then(|| dep.to_string())
        })
        .collect()
}

/// Collects a deck's exam sources: comment lines `% source: <url-or-path>`
/// (repeatable) — the ground truth the AI exam grades against. Like links and
/// requires, they are invisible to the card parser.
pub fn parse_sources(text: &str) -> Vec<String> {
    text.lines()
        .filter_map(|raw| {
            let rest = raw.trim().strip_prefix(MARKUP_COMMENT)?;
            let src = rest.trim().strip_prefix("source:")?.trim();
            (!src.is_empty()).then(|| src.to_string())
        })
        .collect()
}

/// The deck's display title (`% title: <text>`), if it declares one. A
/// display-only name independent of the file name; the first such line wins.
/// Invisible to the card parser, so it never affects card hashes.
pub fn parse_title(text: &str) -> Option<String> {
    text.lines().find_map(|raw| {
        let rest = raw.trim().strip_prefix(MARKUP_COMMENT)?;
        let title = rest.trim().strip_prefix("title:")?.trim();
        (!title.is_empty()).then(|| title.to_string())
    })
}

/// What a trace walks (`% trace: <path description>`), if the deck declares it.
/// A `% trace:` marks the deck as a **trace** — a guided predict-and-verify
/// walk (see [`crate::trace`]) rather than a plain card deck. The first such
/// line wins. Invisible to the card parser, so it never affects card hashes.
pub fn parse_trace(text: &str) -> Option<String> {
    text.lines().find_map(|raw| {
        let rest = raw.trim().strip_prefix(MARKUP_COMMENT)?;
        let desc = rest.trim().strip_prefix("trace:")?.trim();
        (!desc.is_empty()).then(|| desc.to_string())
    })
}

/// Parses a single `% key: value` directive line into a lower-cased key and
/// trimmed value. Returns `None` for non-directive `%` lines: prose comments
/// (key contains whitespace, like `% Then learn with:`), empty key/value, and
/// `link` (handled by [`parse_links`]).
fn directive(raw: &str) -> Option<(String, String)> {
    let rest = raw.trim().strip_prefix(MARKUP_COMMENT)?;
    let (key, value) = rest.split_once(':')?;
    let key = key.trim().to_ascii_lowercase();
    if key.is_empty() || key.contains(char::is_whitespace) || key == "link" {
        return None;
    }
    let value = value.trim();
    (!value.is_empty()).then(|| (key, value.to_string()))
}

/// Collects deck-level `% key: value` directives (e.g. `% mode: line`) from the
/// header — the lines before the first card. Directives after a card front are
/// per-card overrides (handled while parsing the card), so deck-level ones must
/// sit at the top. These are invisible to the card parser and don't affect
/// hashes.
pub fn parse_directives(text: &str) -> Vec<(String, String)> {
    text.lines()
        .take_while(|raw| !raw.starts_with(MARKUP_FRONT))
        .filter_map(directive)
        .collect()
}

/// Parses deck text into cards. `subject` is the deck's file name and becomes
/// part of every card's identity hash.
pub fn parse_str(subject: &str, text: &str) -> Result<Vec<Card>, ParseError> {
    let subject: Arc<str> = Arc::from(subject);
    let mut cards = Vec::new();
    let mut state = State::Init;
    let mut partial: Option<PartialCard> = None;

    for (lineno, raw) in text.lines().enumerate() {
        let lineno = lineno + 1;
        let line = raw.trim();
        if line.is_empty() {
            continue;
        }

        // The line is non-empty, so a first character exists.
        let first = line.chars().next().unwrap();

        // A front marker only counts at column 0 of the raw line; indented
        // `#` lines are answer content (shell comments, Rust attributes...).
        let is_front = first == MARKUP_FRONT && raw.starts_with(MARKUP_FRONT);

        match first {
            MARKUP_FRONT if is_front => {
                match state {
                    State::Front => {
                        // Point at the front line that lacks an answer.
                        return Err(ParseError::FrontWithoutBack(partial.unwrap().line));
                    }
                    State::Back | State::Note => {
                        partial.take().unwrap().build(&subject, &mut cards)?;
                    }
                    State::Init => {}
                }
                // `#?` (no space in between) marks a cloze card.
                let rest = &line[MARKUP_FRONT.len_utf8()..];
                let (cloze, rest) = match rest.strip_prefix(MARKUP_CLOZE) {
                    Some(rest) => (true, rest),
                    None => (false, rest),
                };
                let front = rest.trim();
                if front.is_empty() {
                    return Err(ParseError::EmptyFront(lineno));
                }
                partial = Some(PartialCard {
                    front: front.to_string(),
                    back: Vec::new(),
                    note: None,
                    line: lineno,
                    cloze,
                    mode: None,
                    direction: None,
                    image: None,
                    image_back: None,
                    frontend: None,
                    at: None,
                    givens: Vec::new(),
                });
                state = State::Front;
            }
            MARKUP_NOTE => {
                match state {
                    State::Init => return Err(ParseError::NoteBeforeFront(lineno)),
                    State::Front => return Err(ParseError::NoteBeforeBack(lineno)),
                    State::Back | State::Note => {}
                }
                // Strip the marker and one separating space, but keep any
                // further leading whitespace so indented note content (e.g.
                // code inside a ``` fence) survives. Trailing space is dropped.
                let after = &line[MARKUP_NOTE.len_utf8()..];
                let text = after.strip_prefix(' ').unwrap_or(after).trim_end();
                // `partial` is Some whenever state is Back or Note. Further
                // `!` lines extend the note by one line each.
                let note = &mut partial.as_mut().unwrap().note;
                match note {
                    Some(note) => {
                        note.push('\n');
                        note.push_str(text);
                    }
                    None => *note = Some(text.to_string()),
                }
                state = State::Note;
            }
            MARKUP_COMMENT => {
                // A `% key: value` directive inside a card is a per-card
                // override (`mode`, `direction`, `img`, `img-back`, `frontend`);
                // unrecognized keys are ignored, like deck-level directives. `%`
                // lines before the first card are deck-level (handled by
                // parse_directives).
                if state != State::Init
                    && let Some((key, value)) = directive(line)
                {
                    let partial = partial.as_mut().unwrap();
                    match key.as_str() {
                        "mode" => {
                            if let Ok(m) = Mode::from_str(&value, true) {
                                partial.mode = Some(m);
                            }
                        }
                        "direction" => {
                            if let Ok(d) = Direction::from_str(&value, true) {
                                partial.direction = Some(d);
                            }
                        }
                        "img" => partial.image = Some(value),
                        "img-back" => partial.image_back = Some(value),
                        "at" => partial.at = Some(value),
                        "given" => partial.givens.push(value),
                        "frontend" => {
                            if let Ok(f) = Frontend::from_str(&value, true) {
                                partial.frontend = Some(f);
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {
                match state {
                    State::Init => return Err(ParseError::BackBeforeFront(lineno)),
                    State::Note => return Err(ParseError::BackAfterNote(lineno)),
                    State::Front | State::Back => {}
                }
                // Strip a leading backslash only when it escapes a markup
                // character, so an ordinary backslash is left untouched.
                let second = line.chars().nth(1);
                let back_line =
                    if first == MARKUP_ESCAPE && second.is_some_and(|c| MARKUP.contains(&c)) {
                        &line[MARKUP_ESCAPE.len_utf8()..]
                    } else {
                        line
                    };
                partial
                    .as_mut()
                    .unwrap()
                    .back
                    .push((lineno, back_line.to_string()));
                state = State::Back;
            }
        }
    }

    if state == State::Front {
        // A trailing front without an answer; point at its line.
        return Err(ParseError::FrontWithoutBack(partial.unwrap().line));
    }
    if let Some(p) = partial.take() {
        p.build(&subject, &mut cards)?;
    }

    Ok(cards)
}

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

    #[test]
    fn single_card() {
        let cards = parse_str("s", "# front\n\tback").unwrap();
        assert_eq!(1, cards.len());
        assert_eq!("front", cards[0].front);
        assert_eq!(vec!["back"], cards[0].back);
        assert_eq!(None, cards[0].note);
        assert_eq!(1, cards[0].line);
    }

    #[test]
    fn multi_line_back_is_trimmed_per_line() {
        let text = "# front\n\tvar (\n   \t a = 1\n\t)\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(vec!["var (", "a = 1", ")"], cards[0].back);
    }

    #[test]
    fn note_after_back() {
        let cards = parse_str("s", "# front\n\tback\n\t! a note").unwrap();
        assert_eq!(Some("a note".to_string()), cards[0].note);
    }

    #[test]
    fn comments_and_blank_lines_ignored() {
        let text = "% header comment\n\n# front\n\nback\n\n% trailing\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(1, cards.len());
        assert_eq!(vec!["back"], cards[0].back);
    }

    #[test]
    fn escaped_markup_in_back() {
        let cards = parse_str("s", "# front\n\t\\%\n\t\\#\n\t\\!").unwrap();
        assert_eq!(vec!["%", "#", "!"], cards[0].back);
    }

    #[test]
    fn backslash_without_markup_kept_verbatim() {
        let cards = parse_str("s", "# front\n\t\\n is a newline").unwrap();
        assert_eq!(vec!["\\n is a newline"], cards[0].back);
    }

    #[test]
    fn several_cards() {
        let text = "# a\n1\n# b\n2\n3\n! note b\n# c\n4\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(3, cards.len());
        assert_eq!("a", cards[0].front);
        assert_eq!(vec!["2", "3"], cards[1].back);
        assert_eq!(Some("note b".to_string()), cards[1].note);
        assert_eq!("c", cards[2].front);
        assert_eq!(7, cards[2].line);
    }

    #[test]
    fn error_back_before_front() {
        assert_eq!(Err(ParseError::BackBeforeFront(1)), parse_str("s", "back"));
    }

    #[test]
    fn error_front_without_back() {
        assert_eq!(
            Err(ParseError::FrontWithoutBack(1)),
            parse_str("s", "# a\n# b\nback")
        );
        assert_eq!(
            Err(ParseError::FrontWithoutBack(2)),
            parse_str("s", "% x\n# a\n")
        );
    }

    #[test]
    fn error_note_placement() {
        assert_eq!(
            Err(ParseError::NoteBeforeFront(1)),
            parse_str("s", "! note")
        );
        assert_eq!(
            Err(ParseError::NoteBeforeBack(2)),
            parse_str("s", "# a\n! note")
        );
        assert_eq!(
            Err(ParseError::BackAfterNote(4)),
            parse_str("s", "# a\nback\n! note\nmore back")
        );
    }

    #[test]
    fn links_are_collected_and_stay_comments() {
        let text = "% link: https://docs.rs/tokio\n\
                    % a normal comment\n\
                    %link:https://example.org/spec\n\
                    # front\n\
                    \tback\n\
                    % link:\n";
        assert_eq!(
            vec!["https://docs.rs/tokio", "https://example.org/spec"],
            parse_links(text)
        );
        // The card parser is unaffected.
        let cards = parse_str("s", text).unwrap();
        assert_eq!(1, cards.len());
        assert_eq!(vec!["back"], cards[0].back);
    }

    #[test]
    fn multi_line_note() {
        let cards = parse_str("s", "# a\nback\n! one\n! two\n! three").unwrap();
        assert_eq!(Some("one\ntwo\nthree".to_string()), cards[0].note);
    }

    #[test]
    fn requires_are_collected() {
        let text = "% requires: basics\n\
                    %requires:more.txt\n\
                    % link: https://example.org\n\
                    % a normal comment\n\
                    # front\n\tback\n";
        assert_eq!(vec!["basics", "more.txt"], parse_requires(text));
    }

    #[test]
    fn sources_are_collected_and_stay_comments() {
        let text = "% source: https://doc.rust-lang.org/book/ch04.html\n\
                    %source:notes.md\n\
                    % requires: basics\n\
                    % a normal comment\n\
                    # front\n\tback\n\
                    % source:\n";
        assert_eq!(
            vec!["https://doc.rust-lang.org/book/ch04.html", "notes.md"],
            parse_sources(text)
        );
        // The card parser is unaffected by source lines.
        let cards = parse_str("s", text).unwrap();
        assert_eq!(1, cards.len());
        assert_eq!(vec!["back"], cards[0].back);
    }

    #[test]
    fn directives_are_collected() {
        let text = "% mode: line\n\
                    %  Scheduler:SM2 \n\
                    % link: https://example.org\n\
                    % Then learn it with: alix\n\
                    % a plain comment\n\
                    # front\n\tback\n";
        assert_eq!(
            vec![
                ("mode".to_string(), "line".to_string()),
                // Key is lower-cased; value keeps its case.
                ("scheduler".to_string(), "SM2".to_string()),
            ],
            parse_directives(text)
        );
        // The card parser is unaffected by directive lines.
        let cards = parse_str("s", text).unwrap();
        assert_eq!(1, cards.len());
    }

    #[test]
    fn per_card_mode_directive_is_parsed() {
        let text = "# a\n% mode: choice\n\tx\n# b\n\ty\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(Some(Mode::Choice), cards[0].mode);
        assert_eq!(None, cards[1].mode); // no per-card directive
    }

    #[test]
    fn per_card_direction_directive_is_parsed() {
        // parse_str records the declared direction; expansion happens at load.
        let cards = parse_str("s", "# a\n% direction: both\n\tx\n# b\n\ty\n").unwrap();
        assert_eq!(Some(Direction::Both), cards[0].direction);
        assert_eq!(None, cards[1].direction);
    }

    #[test]
    fn per_card_image_and_frontend_directives_are_parsed() {
        let text = "# q\n% img: moon.png\n% img-back: phase.png\n% frontend: web\n\tWaxing\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(Some(PathBuf::from("moon.png")), cards[0].image);
        assert_eq!(Some(PathBuf::from("phase.png")), cards[0].image_back);
        assert_eq!(Some(Frontend::Web), cards[0].frontend);
    }

    #[test]
    fn cloze_card_ignores_image_directive() {
        // `% img:` is only stamped on plain cards; cloze sub-cards keep None.
        let cards = parse_str("s", "#? f\n% img: x.png\n{{a}} b\n").unwrap();
        assert_eq!(None, cards[0].image);
    }

    #[test]
    fn per_card_at_locator_is_parsed_verbatim() {
        // The trace locator keeps its colons and ranges as written.
        let cards = parse_str("s", "# predict\n% at: src/card.rs:151-158\n\tpoint\n").unwrap();
        assert_eq!(Some("src/card.rs:151-158".to_string()), cards[0].at);
        // A card without one stays None.
        let bare = parse_str("s", "# q\n\ta\n").unwrap();
        assert_eq!(None, bare[0].at);
    }

    #[test]
    fn per_card_given_lines_are_collected_in_order() {
        let text = "# q\n\
                    % given: state — the parser position\n\
                    % given: partial — the card being assembled\n\
                    \tkey point\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(
            vec![
                "state — the parser position".to_string(),
                "partial — the card being assembled".to_string(),
            ],
            cards[0].givens
        );
        // A card without any `% given:` has an empty list.
        assert!(parse_str("s", "# q\n\ta\n").unwrap()[0].givens.is_empty());
    }

    #[test]
    fn trace_marks_a_deck_and_keeps_the_path() {
        assert_eq!(
            Some("how a keypress becomes a saved grade".to_string()),
            parse_trace("% trace: how a keypress becomes a saved grade\n# f\n\tb\n")
        );
        assert_eq!(None, parse_trace("# f\n\tb\n"));
        assert_eq!(None, parse_trace("% trace:\n# f\n\tb\n")); // empty
    }

    #[test]
    fn title_is_parsed_keeping_spaces_and_colons() {
        assert_eq!(
            Some("Rust: The Book".to_string()),
            parse_title("% title: Rust: The Book\n# f\n\tb\n")
        );
        assert_eq!(None, parse_title("# f\n\tb\n"));
        assert_eq!(None, parse_title("% title:\n# f\n\tb\n")); // empty
    }

    #[test]
    fn directives_are_header_only() {
        // A `% mode:` after a card front is a per-card override, not deck-level.
        assert!(parse_directives("# a\n% mode: choice\n\tx\n").is_empty());
        // In the header it is collected.
        assert_eq!(
            vec![("mode".to_string(), "line".to_string())],
            parse_directives("% mode: line\n# a\n\tx\n")
        );
    }

    #[test]
    fn note_preserves_interior_indentation() {
        // Only the marker and one separating space are stripped; further
        // leading whitespace (e.g. indented code in a fence) is kept.
        let text = "# a\nback\n! ```rust\n! fn main() {\n!     let x = 1;\n! }\n! ```";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(
            Some("```rust\nfn main() {\n    let x = 1;\n}\n```".to_string()),
            cards[0].note
        );
    }

    #[test]
    fn note_lines_may_be_separated_by_blanks_and_comments() {
        let text = "# a\nback\n! one\n\n% comment\n! two\n# b\nback b\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(2, cards.len());
        assert_eq!(Some("one\ntwo".to_string()), cards[0].note);
        assert_eq!(None, cards[1].note);
    }

    #[test]
    fn multi_line_note_on_cloze_cards() {
        let cards = parse_str("s", "#? f\n{{a}} b\n! one\n! two").unwrap();
        assert_eq!(Some("one\ntwo".to_string()), cards[0].note);
    }

    #[test]
    fn error_empty_front() {
        assert_eq!(Err(ParseError::EmptyFront(1)), parse_str("s", "#\nback"));
        assert_eq!(Err(ParseError::EmptyFront(1)), parse_str("s", "#?\nback"));
    }

    #[test]
    fn indented_hash_is_answer_content() {
        // Code answers contain '#' lines (shell comments, Rust attributes);
        // only a '#' at column 0 starts a new card.
        let text = "# Dockerfile for a bin project\n\
                    \tFROM rust\n\
                    \t# Pre-built dependencies\n\
                    \tRUN cargo build\n\
                    # Which attribute exports an async fn?\n\
                    \t#[uniffi::export(async_runtime = \"tokio\")]\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(2, cards.len());
        assert_eq!(
            vec!["FROM rust", "# Pre-built dependencies", "RUN cargo build"],
            cards[0].back
        );
        assert_eq!(
            vec!["#[uniffi::export(async_runtime = \"tokio\")]"],
            cards[1].back
        );
    }

    #[test]
    fn indented_hash_before_any_front_is_an_error() {
        assert_eq!(
            Err(ParseError::BackBeforeFront(1)),
            parse_str("s", "\t# comment\n")
        );
    }

    #[test]
    fn escaped_hash_and_indented_hash_yield_the_same_back_line() {
        // Both spellings must produce identical content (and therefore the
        // same card hash), so a deck using the escape keeps its progress.
        let escaped = parse_str("s", "# f\n\t\\# x\n").unwrap();
        let indented = parse_str("s", "# f\n\t# x\n").unwrap();
        assert_eq!(escaped[0].back, indented[0].back);
        assert_eq!(escaped[0].id(), indented[0].id());
    }

    #[test]
    fn indented_cloze_marker_is_answer_content() {
        let cards = parse_str("s", "# f\n\t#? not a cloze front\n").unwrap();
        assert_eq!(vec!["#? not a cloze front"], cards[0].back);
    }

    #[test]
    fn cloze_front_expands_to_sub_cards() {
        let text = "#? Complete the quote\n\tTo {{be}} or not to {{be}}\n\t! Hamlet\n";
        let cards = parse_str("s", text).unwrap();
        assert_eq!(2, cards.len());
        assert_eq!("Complete the quote", cards[0].front);
        assert_eq!(vec!["To ____ or not to […]"], cards[0].context);
        assert_eq!(vec!["be"], cards[0].back);
        assert_eq!(Some("Hamlet".to_string()), cards[0].note);
        assert_eq!(vec!["To […] or not to ____"], cards[1].context);
        assert_ne!(cards[0].id(), cards[1].id());
    }

    #[test]
    fn cloze_marker_requires_no_space() {
        // "# ? ..." is a plain card whose front starts with '?'.
        let cards = parse_str("s", "# ? matches one char\n\tglob\n").unwrap();
        assert_eq!(1, cards.len());
        assert_eq!("? matches one char", cards[0].front);
        assert!(cards[0].context.is_empty());
    }

    #[test]
    fn braces_in_plain_cards_stay_literal() {
        // Code answers contain braces; without the '#?' marker they are never
        // treated as cloze holes, and the identity hash (over the back lines
        // verbatim) is unaffected.
        let cards = parse_str("s", "# main\n\tfunc main() {}\n\tx := T{ a, b }\n").unwrap();
        assert_eq!(1, cards.len());
        assert_eq!(vec!["func main() {}", "x := T{ a, b }"], cards[0].back);
        assert!(cards[0].hash_lines.is_none());
    }

    #[test]
    fn cloze_errors_carry_line_numbers() {
        assert_eq!(
            Err(ParseError::ClozeWithoutHoles(1)),
            parse_str("s", "#? front\n\tno holes\n")
        );
        assert_eq!(
            Err(ParseError::UnclosedClozeHole(3)),
            parse_str("s", "#? front\n\tok {{fine}}\n\tbad {{oops\n")
        );
        assert_eq!(
            Err(ParseError::EmptyClozeHole(2)),
            parse_str("s", "#? front\n\tbad {{}} here\n")
        );
    }
}