alix 0.8.0

A learning tool built for understanding, not just remembering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use chrono::{DateTime, Utc};
use rs_fsrs::{Card as FsrsCard, FSRS, Parameters, Rating, State as RawState};

use crate::{
    depth::Depth,
    store::{CardState, FsrsState},
};

#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Grade {
    Fail,
    Partial,
    Pass,
}

impl Grade {
    pub fn passed(self) -> bool {
        matches!(self, Grade::Pass | Grade::Partial)
    }
}

/// A `total` of 0 is a `Pass`: there's no rubric to miss.
pub fn keypoint_grade(covered: usize, total: usize) -> Grade {
    if total == 0 || covered >= total {
        Grade::Pass
    } else if covered == 0 {
        Grade::Fail
    } else {
        Grade::Partial
    }
}

/// `Send + Sync` so a `Session` (which boxes one) can cross threads (e.g. the
/// frb mobile bridge).
pub trait Scheduler: Send + Sync {
    fn due_at(&self, state: &CardState, depth: Depth) -> u64;

    /// `propagated` marks a review credited down from a pass at a higher
    /// depth, not answered directly; the schedule math is identical either way.
    fn apply(
        &self,
        state: &mut CardState,
        depth: Depth,
        grade: Grade,
        now_ms: u64,
        propagated: bool,
    );

    /// A card with no FSRS state yet at `depth` is left untouched: there's no
    /// interval to preserve.
    fn reanchor(&self, state: &mut CardState, depth: Depth, now_ms: u64);

    fn is_due(&self, state: &CardState, depth: Depth, now_ms: u64) -> bool {
        self.due_at(state, depth) <= now_ms
    }

    fn introduction_cooldown_ms(&self) -> u64;
}

/// Recognition holds far longer than production; 0.85 is inferred from the
/// interval curve, not measured (ADR 0033 records the provenance), which is
/// why it is a config key and not a constant learners cannot move.
pub const DEFAULT_RECOGNIZE_RETENTION: f64 = 0.85;

/// Doubles as `Session`'s same-card re-serve floor: one knob moves both gaps.
pub const DEFAULT_INTRODUCTION_COOLDOWN_MS: u64 = 5 * 60 * 1000;

/// Deliberately a constant, not a config key: an expert knob with no
/// pre-exam feedback loop; base `retention` is the pressure valve.
pub const DEADLINE_RETENTION: f64 = 0.95;

/// The due ceiling compensates an rs-fsrs quirk: it clamps the interval
/// BEFORE separating grades, so a mature card graded Pass can still land
/// past `max_interval_days`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DeadlineTuning {
    pub retention: f64,
    // How far the ramp has progressed (0 outside the window, 1 at the
    // deadline), kept so a second engine can ramp from ITS OWN base instead
    // of inheriting the recall-resolved retention (Codex tenth pass, P1).
    pub ramp_progress: f64,
    pub max_interval_days: i32,
    pub due_ceiling_ms: u64,
}

impl DeadlineTuning {
    // The same ramp applied to another base: cap-only tuning (progress 0)
    // leaves that base untouched.
    fn retention_for(self, base: f64) -> f64 {
        (base + (DEADLINE_RETENTION - base) * self.ramp_progress).max(base)
    }
}

/// `None` past the date is deliberate: the ramp releases rather than
/// erroring. `today`/`due_ceiling_ms` are injected, not computed inline, so
/// this stays deterministic for tests.
pub fn deadline_tuning(
    deadline: chrono::NaiveDate,
    ramp_days: u32,
    base_retention: f64,
    today: chrono::NaiveDate,
    due_ceiling_ms: u64,
) -> Option<DeadlineTuning> {
    let days_left = (deadline - today).num_days();
    if days_left < 0 {
        return None;
    }
    let ramp_progress = if ramp_days == 0 || days_left >= i64::from(ramp_days) {
        0.0
    } else {
        let w = f64::from(ramp_days);
        (w - days_left as f64) / w
    };
    let retention = (base_retention + (DEADLINE_RETENTION - base_retention) * ramp_progress)
        .max(base_retention);
    Some(DeadlineTuning {
        retention,
        ramp_progress,
        max_interval_days: days_left.max(1) as i32,
        due_ceiling_ms,
    })
}

const DAY_MS: u64 = 86_400 * 1000;

/// Hold step for a card that passed once but hasn't earned its second Good yet
/// (10 min, matching FSRS's New+Good step).
const LEARNING_HOLD_MS: u64 = 10 * 60 * 1000;

fn ms_to_dt(ms: u64) -> DateTime<Utc> {
    DateTime::from_timestamp_millis(ms as i64).unwrap_or_default()
}

fn dt_to_ms(dt: DateTime<Utc>) -> u64 {
    dt.timestamp_millis().max(0) as u64
}

fn rating_for(grade: Grade) -> Rating {
    match grade {
        Grade::Fail => Rating::Again,
        Grade::Partial => Rating::Hard,
        Grade::Pass => Rating::Good,
    }
}

fn raw_state(s: u8) -> RawState {
    match s {
        1 => RawState::Learning,
        2 => RawState::Review,
        3 => RawState::Relearning,
        _ => RawState::New,
    }
}

fn to_fsrs_card(s: &FsrsState) -> FsrsCard {
    FsrsCard {
        due: ms_to_dt(s.due_ms),
        stability: s.stability,
        difficulty: s.difficulty,
        elapsed_days: 0, // rs-fsrs recomputes this from `last_review`
        scheduled_days: s.scheduled_days as i64,
        reps: s.reps as i32,
        lapses: s.lapses as i32,
        state: raw_state(s.state),
        last_review: ms_to_dt(s.last_review_ms),
    }
}

fn from_fsrs_card(c: &FsrsCard) -> FsrsState {
    FsrsState {
        stability: c.stability,
        difficulty: c.difficulty,
        reps: c.reps.max(0) as u32,
        lapses: c.lapses.max(0) as u32,
        state: c.state as u8,
        scheduled_days: c.scheduled_days.max(0) as u32,
        last_review_ms: dt_to_ms(c.last_review),
        due_ms: dt_to_ms(c.due),
        // The learning-steps counter is alix's, not rs-fsrs's; `apply` carries it.
        ..Default::default()
    }
}

/// Always seeds `New`, ignoring `_state`: there is no pre-FSRS carry-over to
/// derive from.
fn seed_card(_state: &CardState, now_ms: u64) -> FsrsCard {
    let mut c = FsrsCard::new();
    c.last_review = ms_to_dt(now_ms);
    c.due = ms_to_dt(now_ms);
    c
}

pub struct Fsrs {
    fsrs: FSRS,
    // Recognition decays slower than production, so Recognize runs its own
    // desired retention (ADR 0033); one mechanism, two tunings.
    recognize_fsrs: FSRS,
    introduction_cooldown_ms: u64,
    due_ceiling_ms: Option<u64>,
}

impl Fsrs {
    pub fn new(retention: f64, introduction_cooldown_ms: u64) -> Self {
        Self::tuned(
            retention,
            DEFAULT_RECOGNIZE_RETENTION,
            introduction_cooldown_ms,
            None,
        )
    }

    pub fn tuned(
        retention: f64,
        recognize_retention: f64,
        introduction_cooldown_ms: u64,
        deadline: Option<DeadlineTuning>,
    ) -> Self {
        let parameters = fsrs_parameters(retention, deadline);
        let recognize_parameters = fsrs_parameters(
            recognize_retention,
            deadline.map(|t| DeadlineTuning {
                retention: t.retention_for(recognize_retention),
                ..t
            }),
        );
        Self {
            fsrs: FSRS::new(parameters),
            recognize_fsrs: FSRS::new(recognize_parameters),
            introduction_cooldown_ms,
            due_ceiling_ms: deadline.map(|t| t.due_ceiling_ms),
        }
    }

    fn engine(&self, depth: Depth) -> &FSRS {
        match depth {
            Depth::Recognize => &self.recognize_fsrs,
            Depth::Recall | Depth::Reconstruct => &self.fsrs,
        }
    }
}

fn fsrs_parameters(retention: f64, deadline: Option<DeadlineTuning>) -> Parameters {
    Parameters {
        request_retention: deadline.map_or(retention, |t| t.retention),
        maximum_interval: deadline.map_or(36500, |t| t.max_interval_days),
        enable_short_term: true,
        ..Parameters::default()
    }
}

impl Default for Fsrs {
    fn default() -> Self {
        Self::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS)
    }
}

impl Scheduler for Fsrs {
    fn due_at(&self, state: &CardState, depth: Depth) -> u64 {
        match state.schedule(depth) {
            Some(s) => s.due_ms,
            // Established at another depth: due now, skipping the introduction
            // warm-up (its own schedule is created lazily on the first grade).
            None if state.recognize.is_some()
                || state.recall.is_some()
                || state.reconstruct.is_some() =>
            {
                0
            }
            // Anchor the warm-up on the introduction. An entry with no
            // timestamp and no schedule cannot arise through the session (the
            // Seen press writes before departure), so the epoch fallback is
            // unreachable rather than a serving hazard.
            None => state
                .introduced_ms
                .unwrap_or_default()
                .saturating_add(self.introduction_cooldown_ms),
        }
    }

    fn introduction_cooldown_ms(&self) -> u64 {
        self.introduction_cooldown_ms
    }

    fn apply(
        &self,
        state: &mut CardState,
        depth: Depth,
        grade: Grade,
        now_ms: u64,
        propagated: bool,
    ) {
        let current = state.schedule(depth).copied();
        let (card, pre_state, prev_goods) = match &current {
            Some(s) => (to_fsrs_card(s), s.state, s.learning_goods),
            None => (seed_card(state, now_ms), 0, 0),
        };
        let info = self
            .engine(depth)
            .next(card, ms_to_dt(now_ms), rating_for(grade));
        let mut next = from_fsrs_card(&info.card);

        // Graduation gate: the learning phase (state 0|1) needs two full Goods
        // before Review; a Fail resets the count, Relearning re-graduates on
        // one Good.
        let learning = matches!(pre_state, 0 | 1);
        let mut goods = prev_goods;
        if learning {
            match grade {
                Grade::Pass => goods = goods.saturating_add(1),
                Grade::Fail => goods = 0,
                Grade::Partial => {}
            }
        }
        if next.state == 2 && learning && goods < 2 {
            // rs-fsrs would graduate on this single Good; hold in Learning instead.
            next.state = 1;
            next.scheduled_days = 0;
            next.due_ms = now_ms.saturating_add(LEARNING_HOLD_MS);
        }
        next.learning_goods = if next.state == 2 { 0 } else { goods };

        // Only clamps dues beyond the ceiling; `reanchor` is deliberately not
        // bounded by it.
        if let Some(ceiling) = self.due_ceiling_ms
            && next.due_ms > ceiling
        {
            next.due_ms = ceiling;
            next.scheduled_days = (ceiling.saturating_sub(now_ms) / DAY_MS) as u32;
        }

        let Some(slot) = state.schedule_slot(depth) else {
            return;
        };
        *slot = Some(next);
        state.record_review(now_ms, grade, depth, propagated);
    }

    fn reanchor(&self, state: &mut CardState, depth: Depth, now_ms: u64) {
        if let Some(Some(f)) = state.schedule_slot(depth) {
            let interval_ms = u64::from(f.scheduled_days) * DAY_MS;
            f.due_ms = now_ms.saturating_add(interval_ms);
        }
    }
}

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

    #[test]
    fn due_at_for_an_unscheduled_card_is_one_introduction_cooldown_out() {
        let sched = Fsrs::default();
        let mut s = CardState::introduced_at(1000);
        assert_eq!(
            sched.due_at(&s, Depth::Recall),
            1000 + DEFAULT_INTRODUCTION_COOLDOWN_MS
        );
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 1000, false);
        assert!(s.recall.is_some());
        assert!(sched.due_at(&s, Depth::Recall) != 1000 + DEFAULT_INTRODUCTION_COOLDOWN_MS);
    }

    #[test]
    fn due_at_is_immediate_at_a_depth_scheduled_elsewhere() {
        let sched = Fsrs::default();
        let mut s = CardState::introduced_at(1_000);
        s.recall = Some(FsrsState {
            due_ms: u64::MAX,
            ..Default::default()
        });
        assert_eq!(0, sched.due_at(&s, Depth::Reconstruct), "immediately due");
        assert!(sched.is_due(&s, Depth::Reconstruct, 1));
        assert_eq!(u64::MAX, sched.due_at(&s, Depth::Recall));
        let fresh = CardState::introduced_at(1_000);
        assert_eq!(
            1_000 + DEFAULT_INTRODUCTION_COOLDOWN_MS,
            sched.due_at(&fresh, Depth::Reconstruct)
        );
    }

    #[test]
    fn apply_writes_only_the_chosen_depths_schedule() {
        let sched = Fsrs::default();
        let mut st = CardState::introduced_at(0);
        sched.apply(&mut st, Depth::Reconstruct, Grade::Pass, 1_000, false);
        assert!(st.schedule(Depth::Reconstruct).is_some());
        assert!(st.schedule(Depth::Recall).is_none(), "no cross-crediting");
        assert_eq!(Depth::Reconstruct, st.history[0].depth);
    }

    #[test]
    fn apply_on_recognize_creates_its_own_schedule_and_touches_no_other() {
        let sched = Fsrs::default();
        let mut st = CardState::introduced_at(0);
        sched.apply(&mut st, Depth::Recognize, Grade::Pass, 1_000, false);
        assert!(
            st.recognize.is_some(),
            "recognize is an ordinary scheduled depth"
        );
        assert!(st.recall.is_none() && st.reconstruct.is_none());
        assert_eq!(Depth::Recognize, st.history[0].depth);
    }

    #[test]
    fn a_cap_only_deadline_does_not_replace_recognize_retention() {
        let tuned = Fsrs::tuned(
            0.9,
            DEFAULT_RECOGNIZE_RETENTION,
            0,
            Some(DeadlineTuning {
                retention: 0.9,
                ramp_progress: 0.0,
                max_interval_days: 36500,
                due_ceiling_ms: u64::MAX,
            }),
        );
        let plain = Fsrs::new(0.9, 0);
        for sched in [&tuned, &plain] {
            let mut st = CardState::introduced_at(0);
            let mut now = 1_000;
            let mut days = Vec::new();
            for _ in 0..4 {
                sched.apply(&mut st, Depth::Recognize, Grade::Pass, now, false);
                let f = st.recognize.as_ref().unwrap();
                days.push(f.scheduled_days);
                now = f.due_ms.max(now + 1);
            }
            if std::ptr::eq(sched, &tuned) {
                assert_eq!(
                    days,
                    {
                        let mut st = CardState::introduced_at(0);
                        let mut now = 1_000;
                        let mut d = Vec::new();
                        for _ in 0..4 {
                            plain.apply(&mut st, Depth::Recognize, Grade::Pass, now, false);
                            let f = st.recognize.as_ref().unwrap();
                            d.push(f.scheduled_days);
                            now = f.due_ms.max(now + 1);
                        }
                        d
                    },
                    "deadline_ramp = 0 is cap-only and must not replace the \
                     Recognize retention"
                );
            }
        }
    }

    #[test]
    fn a_ramping_deadline_raises_recognize_from_its_own_base() {
        // Mid-ramp, recognize tightens from 0.85 toward the deadline
        // retention, never by inheriting recall's resolved value.
        let tuning = DeadlineTuning {
            retention: 0.925,
            ramp_progress: 0.5,
            max_interval_days: 36500,
            due_ceiling_ms: u64::MAX,
        };
        assert!((tuning.retention_for(0.85) - 0.9).abs() < 1e-9);
        assert!((tuning.retention_for(0.9) - 0.925).abs() < 1e-9);
    }

    #[test]
    fn recognize_runs_its_own_retention_and_schedules_longer() {
        // Same review sequence, laxer desired retention: the recognize engine
        // must produce a longer interval than the recall engine, or the
        // per-depth tuning is wired to nothing.
        let sched = Fsrs::tuned(0.9, 0.7, 0, None);
        let mut st = CardState::introduced_at(0);
        let mut now = 1_000;
        for _ in 0..3 {
            sched.apply(&mut st, Depth::Recall, Grade::Pass, now, false);
            sched.apply(&mut st, Depth::Recognize, Grade::Pass, now, false);
            now = st
                .recall
                .as_ref()
                .map(|f| f.due_ms.max(now + 1))
                .unwrap_or(now + 1);
        }
        let recall_days = st.recall.as_ref().unwrap().scheduled_days;
        let recognize_days = st.recognize.as_ref().unwrap().scheduled_days;
        assert!(
            recognize_days > recall_days,
            "0.7 retention must out-schedule 0.9: recognize {recognize_days}d vs recall {recall_days}d"
        );
    }

    #[test]
    fn apply_stores_the_propagated_marker_on_the_review() {
        let sched = Fsrs::default();
        let mut direct = CardState::introduced_at(0);
        sched.apply(&mut direct, Depth::Recall, Grade::Pass, 1_000, false);
        assert!(!direct.history[0].propagated, "a direct review is unmarked");
        let mut credited = CardState::introduced_at(0);
        sched.apply(&mut credited, Depth::Recall, Grade::Pass, 1_000, true);
        assert!(
            credited.history[0].propagated,
            "a credited review is marked"
        );
        assert_eq!(direct.recall, credited.recall, "same schedule either way");
    }

    #[test]
    fn the_default_introduction_cooldown_is_five_minutes() {
        // Deliberately pinned: changing it changes every default session's
        // rhythm.
        assert_eq!(5 * 60 * 1000, DEFAULT_INTRODUCTION_COOLDOWN_MS);
    }

    #[test]
    fn a_configured_cooldown_moves_the_first_quiz_and_the_floor() {
        let sched = Fsrs::new(0.9, 90_000);
        let fresh = CardState::introduced_at(1_000);
        assert_eq!(1_000 + 90_000, sched.due_at(&fresh, Depth::Recall));
        assert_eq!(90_000, sched.introduction_cooldown_ms());
        assert_eq!(
            DEFAULT_INTRODUCTION_COOLDOWN_MS,
            Fsrs::default().introduction_cooldown_ms()
        );
    }

    #[test]
    fn partly_counts_as_a_pass() {
        let mut s = CardState::introduced_at(0);
        s.record_review(0, Grade::Pass, Depth::Recall, false);
        assert_eq!(1, s.streak);
        assert_eq!(1, s.total_passes);
        s.record_review(1000, Grade::Partial, Depth::Recall, false);
        assert_eq!(2, s.streak);
        assert_eq!(2, s.total_passes);
        assert!(s.history.last().unwrap().grade.passed());
        assert_eq!(Grade::Partial, s.history.last().unwrap().grade);
    }

    #[test]
    fn keypoint_grade_derives_from_coverage() {
        assert_eq!(Grade::Fail, keypoint_grade(0, 5));
        assert_eq!(Grade::Partial, keypoint_grade(1, 5));
        assert_eq!(Grade::Partial, keypoint_grade(4, 5));
        assert_eq!(Grade::Pass, keypoint_grade(5, 5));
        assert_eq!(Grade::Pass, keypoint_grade(0, 0));
    }

    #[test]
    fn fsrs_pass_on_a_new_card_sets_stability_and_schedules_out() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        let f = s.recall.expect("fsrs state set");
        assert!(f.stability > 0.0, "stability should be positive");
        assert!(
            sched.due_at(&s, Depth::Recall) > 0,
            "should be scheduled into the future"
        );
        assert_eq!(1, s.total_reviews);
        assert!(s.history.last().unwrap().grade.passed());
    }

    #[test]
    fn fsrs_partly_grows_stability_less_than_got_it() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut good = CardState::introduced_at(0);
        sched.apply(&mut good, Depth::Recall, Grade::Pass, 0, false);
        let mut hard = CardState::introduced_at(0);
        sched.apply(&mut hard, Depth::Recall, Grade::Partial, 0, false);
        assert!(good.recall.unwrap().stability > hard.recall.unwrap().stability);
    }

    #[test]
    fn fsrs_a_miss_shortens_the_next_interval() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        let pass_interval = sched.due_at(&s, Depth::Recall);
        sched.apply(&mut s, Depth::Recall, Grade::Fail, pass_interval, false);
        let fail_interval = sched
            .due_at(&s, Depth::Recall)
            .saturating_sub(pass_interval);
        assert!(!s.history.last().unwrap().grade.passed());
        assert!(
            fail_interval < pass_interval,
            "a lapse should shorten the interval (fail {fail_interval} vs pass {pass_interval})"
        );
    }

    #[test]
    fn fsrs_new_card_good_enters_a_learning_step() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        let f = s.recall.expect("fsrs state set");
        assert_eq!(1, f.state, "a first Good enters Learning, not Review");
        let due = sched.due_at(&s, Depth::Recall);
        assert!(
            due > 0 && due < DAY_MS,
            "learning step is sub-day (got {due} ms)"
        );
    }

    #[test]
    fn fsrs_two_goods_graduate_to_review() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        let step_due = sched.due_at(&s, Depth::Recall);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, step_due, false);
        assert_eq!(
            2,
            s.recall.expect("fsrs state").state,
            "second Good reaches Review"
        );
        assert!(
            sched.due_at(&s, Depth::Recall) - step_due >= DAY_MS,
            "a graduated card is scheduled at least a day out"
        );
    }

    #[test]
    fn fail_then_one_good_does_not_graduate() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Fail, 0, false);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 60_000, false);
        let f = s.recall.unwrap();
        assert_eq!(1, f.state, "one Good after a fail stays in Learning");
        assert_eq!(1, f.learning_goods);
    }

    #[test]
    fn two_goods_after_a_fail_do_graduate() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Fail, 0, false);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 60_000, false);
        assert_eq!(1, s.recall.unwrap().state);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 700_000, false);
        assert_eq!(2, s.recall.unwrap().state, "two Goods graduate");
    }

    #[test]
    fn a_fail_resets_graduation_progress() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        sched.apply(&mut s, Depth::Recall, Grade::Fail, 60_000, false);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 120_000, false);
        assert_eq!(1, s.recall.unwrap().state, "still Learning after the reset");
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 700_000, false);
        assert_eq!(2, s.recall.unwrap().state);
    }

    #[test]
    fn partial_is_neutral_for_graduation() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        sched.apply(&mut s, Depth::Recall, Grade::Partial, 600_000, false);
        assert_eq!(1, s.recall.unwrap().state);
        assert_eq!(1, s.recall.unwrap().learning_goods);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 1_200_000, false);
        assert_eq!(2, s.recall.unwrap().state);
    }

    #[test]
    fn a_lapsed_card_regraduates_on_one_good() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut s = CardState::introduced_at(0);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 0, false);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 600_000, false);
        sched.apply(&mut s, Depth::Recall, Grade::Fail, 1_200_000, false);
        assert_eq!(3, s.recall.unwrap().state);
        sched.apply(&mut s, Depth::Recall, Grade::Pass, 1_800_000, false);
        assert_eq!(2, s.recall.unwrap().state);
    }

    #[test]
    fn fsrs_overdue_recall_beats_on_time_recall() {
        let sched = Fsrs::new(0.9, DEFAULT_INTRODUCTION_COOLDOWN_MS);
        let mut early = CardState::introduced_at(0);
        sched.apply(&mut early, Depth::Recall, Grade::Pass, 0, false);
        let step_due = sched.due_at(&early, Depth::Recall);
        sched.apply(&mut early, Depth::Recall, Grade::Pass, step_due, false);
        let due = sched.due_at(&early, Depth::Recall);
        let mut late = early.clone();
        sched.apply(&mut early, Depth::Recall, Grade::Pass, due, false);
        sched.apply(&mut late, Depth::Recall, Grade::Pass, due * 3, false);
        assert!(
            late.recall.unwrap().stability > early.recall.unwrap().stability,
            "an overdue-but-recalled card should gain more stability"
        );
    }

    #[test]
    fn deadline_tuning_caps_the_interval_at_days_left() {
        let d = |y, m, dd| chrono::NaiveDate::from_ymd_opt(y, m, dd).unwrap();
        let t = deadline_tuning(d(2026, 9, 1), 14, 0.9, d(2026, 8, 12), 1_000).unwrap();
        assert_eq!(20, t.max_interval_days);
        assert_eq!(0.9, t.retention, "outside the window the base holds");
        assert_eq!(1_000, t.due_ceiling_ms);
    }

    #[test]
    fn deadline_tuning_ramps_retention_inside_the_window() {
        let d = |y, m, dd| chrono::NaiveDate::from_ymd_opt(y, m, dd).unwrap();
        let mid = deadline_tuning(d(2026, 9, 1), 14, 0.9, d(2026, 8, 25), 0).unwrap();
        assert!((mid.retention - 0.925).abs() < 1e-9);
        let last = deadline_tuning(d(2026, 9, 1), 14, 0.9, d(2026, 9, 1), 0).unwrap();
        assert_eq!(DEADLINE_RETENTION, last.retention);
        assert_eq!(1, last.max_interval_days);
        let edge = deadline_tuning(d(2026, 9, 1), 14, 0.9, d(2026, 8, 18), 0).unwrap();
        assert_eq!(0.9, edge.retention);
    }

    #[test]
    fn deadline_tuning_never_lowers_a_higher_base_and_zero_ramp_is_cap_only() {
        let d = |y, m, dd| chrono::NaiveDate::from_ymd_opt(y, m, dd).unwrap();
        let high = deadline_tuning(d(2026, 9, 1), 14, 0.97, d(2026, 9, 1), 0).unwrap();
        assert_eq!(0.97, high.retention, "a personal 0.97 is kept");
        let capped = deadline_tuning(d(2026, 9, 1), 0, 0.9, d(2026, 9, 1), 0).unwrap();
        assert_eq!(0.9, capped.retention, "ramp 0 = cap only");
        assert_eq!(1, capped.max_interval_days);

        let outside = deadline_tuning(d(2026, 9, 1), 14, 0.97, d(2026, 8, 12), 0).unwrap();
        assert_eq!(
            0.97, outside.retention,
            "outside the ramp the higher base holds"
        );
    }

    #[test]
    fn reanchor_converts_each_scheduled_day_to_milliseconds() {
        let mut state = CardState {
            recall: Some(FsrsState {
                scheduled_days: 2,
                ..Default::default()
            }),
            ..Default::default()
        };
        Fsrs::default().reanchor(&mut state, Depth::Recall, 1_234);
        assert_eq!(1_234 + 2 * 86_400_000, state.recall.unwrap().due_ms);
    }

    #[test]
    fn fsrs_conversion_preserves_every_persisted_source_field() {
        let source = FsrsCard {
            due: ms_to_dt(9_000),
            stability: 2.5,
            difficulty: 7.5,
            elapsed_days: 4,
            scheduled_days: 6,
            reps: 8,
            lapses: 3,
            state: RawState::Review,
            last_review: ms_to_dt(8_000),
        };
        let state = from_fsrs_card(&source);
        assert_eq!(2.5, state.stability);
        assert_eq!(7.5, state.difficulty);
        assert_eq!(8, state.reps);
        assert_eq!(3, state.lapses);
        assert_eq!(2, state.state);
        assert_eq!(6, state.scheduled_days);
        assert_eq!(8_000, state.last_review_ms);
        assert_eq!(9_000, state.due_ms);
    }

    #[test]
    fn a_seeded_fsrs_card_is_new_and_anchored_at_the_review_time() {
        let card = seed_card(&CardState::default(), 12_345);
        assert_eq!(RawState::New, card.state);
        assert_eq!(ms_to_dt(12_345), card.last_review);
        assert_eq!(ms_to_dt(12_345), card.due);
    }

    #[test]
    fn fsrs_parameters_preserve_deadline_tuning_and_short_term_steps() {
        let parameters = fsrs_parameters(
            0.83,
            Some(DeadlineTuning {
                retention: 0.96,
                ramp_progress: 0.0,
                max_interval_days: 7,
                due_ceiling_ms: 9_000,
            }),
        );
        assert_eq!(0.96, parameters.request_retention);
        assert_eq!(7, parameters.maximum_interval);
        assert!(parameters.enable_short_term);
    }

    #[test]
    fn deadline_tuning_releases_past_the_date() {
        let d = |y, m, dd| chrono::NaiveDate::from_ymd_opt(y, m, dd).unwrap();
        assert!(deadline_tuning(d(2026, 9, 1), 14, 0.9, d(2026, 9, 2), 0).is_none());
    }

    #[test]
    fn a_deadline_ceiling_bounds_the_due_date_where_the_raw_cap_does_not() {
        let now = 100 * 86_400_000u64;
        let ceiling = now + 3 * 86_400_000;
        let sched = Fsrs::tuned(
            0.9,
            DEFAULT_RECOGNIZE_RETENTION,
            1_000,
            Some(DeadlineTuning {
                retention: 0.9,
                ramp_progress: 0.0,
                max_interval_days: 3,
                due_ceiling_ms: ceiling,
            }),
        );
        let mut st = CardState::introduced_at(0);
        st.recall = Some(FsrsState {
            stability: 200.0,
            difficulty: 5.0,
            state: 2,
            reps: 10,
            scheduled_days: 90,
            last_review_ms: 0,
            due_ms: 0,
            ..Default::default()
        });
        sched.apply(&mut st, Depth::Recall, Grade::Pass, now, false);
        let s = st.recall.unwrap();
        assert!(
            s.due_ms <= ceiling,
            "due {} must not pass the ceiling {ceiling}",
            s.due_ms
        );
        assert!(
            s.scheduled_days <= 3,
            "scheduled_days consistent with the ceiling"
        );

        let mut free = CardState::introduced_at(0);
        free.recall = Some(FsrsState {
            stability: 200.0,
            difficulty: 5.0,
            state: 2,
            reps: 10,
            scheduled_days: 90,
            last_review_ms: 0,
            due_ms: 0,
            ..Default::default()
        });
        Fsrs::new(0.9, 1_000).apply(&mut free, Depth::Recall, Grade::Pass, now, false);
        assert!(free.recall.unwrap().scheduled_days > 3);
    }
}