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
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
};

use alix::{
    assemble::{load_decks, open_store, store_path_for},
    card::Card,
    config::Config,
    deck::{Deck, DeckState},
    depth::Depth,
    scheduler::{Fsrs, Scheduler},
    state,
    store::Store,
    time::{humanize_ms, now_ms},
    workspace,
};
use anyhow::{Context, Result, bail};

use crate::{
    DeckArgs, ResetArgs,
    common::{confirm, expand_target},
};

// One depth's cell: its state label plus its due, `-` with no schedule.
fn depth_cell(state: &alix::store::CardState, scheduler: &Fsrs, depth: Depth, now: u64) -> String {
    let Some(fsrs) = state.schedule(depth) else {
        return "-".to_string();
    };
    let label = state_label(Some(fsrs.state));
    let due = scheduler.due_at(state, depth);
    if due <= now {
        format!("{label} due")
    } else {
        format!("{label} {}", humanize_ms(due - now))
    }
}

fn state_label(fsrs_state: Option<u8>) -> &'static str {
    match fsrs_state {
        Some(1) => "learn",
        Some(2) => "review",
        Some(3) => "relearn",
        Some(_) => "new",
        None => "-",
    }
}

pub(crate) fn stats(args: DeckArgs) -> Result<()> {
    let config = Config::load(args.config.as_deref())?;
    let now = now_ms();

    let target = expand_target(&args.target, &config)?;
    for path in &target.decks {
        let store = target.store_for_deck(path, args.store.as_deref())?;
        let deck = Deck::load(path)?;
        let review = config.review.for_workspace(&workspace::content_root(path));
        let scheduler = Fsrs::new(review.retention, review.introduction_cooldown_ms);

        let mut due_now = 0usize;
        let mut due_24h = 0usize;
        let mut due_now_reconstruct = 0usize;
        let mut due_now_recognize = 0usize;
        let mut reviews = 0u32;
        let mut passes = 0u32;
        for card in &deck.cards {
            if let Some(state) = card.id().and_then(|id| store.progress(&id)) {
                // Retired cards don't count as due, but still count toward
                // the review totals below.
                if !alix::session::is_retired(card, &store, review.retire_after_days) {
                    let due = scheduler.due_at(state, Depth::Recall);
                    if due <= now {
                        due_now += 1;
                    } else if due <= now + 86_400_000 {
                        due_24h += 1;
                    }
                    if scheduler.is_due(state, Depth::Reconstruct, now) {
                        due_now_reconstruct += 1;
                    }
                    if scheduler.is_due(state, Depth::Recognize, now) {
                        due_now_recognize += 1;
                    }
                }
                reviews += state.total_reviews;
                passes += state.total_passes;
            }
        }
        let deck_id = deck.deck_token.as_deref().unwrap_or_default();
        // Personal cards count toward "due" (now and within 24h), never toward
        // the card count below: they aren't deck content.
        let personal = alix::personal::read(&deck.path, &deck.subject).cards;
        due_now += alix::session::count_eligible(
            &personal,
            &store,
            &scheduler,
            Depth::Recall,
            now,
            review.retire_after_days,
        );
        // Derived, not independently counted, so the two figures can't diverge.
        let due_now_recall = due_now;
        due_24h += alix::session::count_due_soon(
            &personal,
            &store,
            &scheduler,
            Depth::Recall,
            now,
            86_400_000,
            review.retire_after_days,
        );

        let state = match deck.state(&store) {
            DeckState::NotStarted => "not started",
            DeckState::Started => "in progress",
            DeckState::ExamDue => "exam due",
            DeckState::Finished if store.deck_mastered(deck_id) => "mastered ✓",
            DeckState::Finished => "finished ✓",
        };
        println!("{} ({} cards)", deck.display_name(), deck.cards.len());
        println!("  state:   {state}");
        println!("  due:     {due_now} now, {due_24h} within 24h");
        println!("  due now (recognize):   {due_now_recognize}");
        println!("  due now (recall):      {due_now_recall}");
        println!("  due now (reconstruct): {due_now_reconstruct}");
        if reviews > 0 {
            println!(
                "  reviews: {reviews} total, {:.0}% passed",
                100.0 * passes as f64 / reviews as f64
            );
        }
    }
    Ok(())
}

pub(crate) fn list(args: DeckArgs) -> Result<()> {
    let config = Config::load(args.config.as_deref())?;
    let now = now_ms();

    let target = expand_target(&args.target, &config)?;
    for path in &target.decks {
        let store = target.store_for_deck(path, args.store.as_deref())?;
        let deck = Deck::load(path)?;
        let review = config.review.for_workspace(&workspace::content_root(path));
        let scheduler = Fsrs::new(review.retention, review.introduction_cooldown_ms);
        println!("{}", deck.display_name());
        for card in &deck.cards {
            let cells = match card.id().and_then(|id| store.progress(&id)) {
                Some(state) => {
                    // A retired card's due time is moot until `alix reset`.
                    if alix::session::is_retired(card, &store, review.retire_after_days) {
                        "resting".to_string()
                    } else {
                        [Depth::Recognize, Depth::Recall, Depth::Reconstruct]
                            .map(|depth| {
                                format!("{:>11}", depth_cell(state, &scheduler, depth, now))
                            })
                            .join("|")
                    }
                }
                None => format!("{0:>11}|{0:>11}|{0:>11}", "-"),
            };
            let front: String = card.front.chars().take(60).collect();
            println!("  [{cells}] {front}");
        }
    }
    Ok(())
}

fn select_reset_ids(cards: &[Card], card: Option<&str>) -> Vec<(String, String)> {
    let stamped: Vec<(String, &Card)> = cards.iter().filter_map(|c| Some((c.id()?, c))).collect();
    // Exact id match only fires when some card actually carries that id, so
    // an ordinary front-substring is never mistaken for an id.
    let exact = card.filter(|q| stamped.iter().any(|(id, _)| id == q));
    let needle = card.filter(|_| exact.is_none()).map(str::to_lowercase);
    stamped
        .into_iter()
        .filter(|(id, c)| match (exact, &needle) {
            (Some(want), _) => id.as_str() == want,
            (None, Some(text)) => c.front.to_lowercase().contains(text),
            (None, None) => true,
        })
        .map(|(id, c)| (id, c.front.clone()))
        .collect()
}

pub(crate) fn reset(args: ResetArgs) -> Result<()> {
    let config = Config::load(args.config.as_deref())?;

    // `--orphans` is explicit opt-in only, never folded into a plain reset.
    if args.orphans {
        return reset_orphans(&args, &config);
    }

    // Opened only by the branches that use it (`--all`, exact `--card`): a
    // target reset resolves the TARGET's store below, and an unrelated
    // store's health must not gate it.
    let default_store = || {
        open_store(
            args.store
                .clone()
                .or_else(|| config.decks_dir().map(|d| workspace::root_store_path(&d))),
        )
    };

    // `store.len()` counts personal-card schedules too, so a store holding
    // only personal cards still reports something to reset.
    if args.all {
        let mut store = default_store()?;
        let n = store.len();
        if n == 0 {
            println!("No stored progress to reset.");
            return Ok(());
        }
        if !confirm(&format!("Reset progress for all {n} card(s)?"), args.yes)? {
            println!("Cancelled.");
            return Ok(());
        }
        store.clear();
        store.save()?;
        println!("Reset {n} card(s).");
        return Ok(());
    }

    let exact_id = args
        .card
        .as_deref()
        .filter(|c| alix::token::parse_prefixed_card_id(c).is_some());
    if let Some(id) = exact_id.filter(|_| args.target.is_none()) {
        let id = id.to_string();
        let mut store = default_store()?;
        return reset_ids(
            &mut store,
            vec![(id.clone(), String::new())],
            format!("card {id}"),
            args.card.as_deref(),
            false,
            args.yes,
        );
    }

    let Some(target_path) = &args.target else {
        bail!("name a deck, folder, or workspace to reset, or pass `--card <id>` or `--all`");
    };
    let target = expand_target(target_path, &config)?;
    let deck_paths = target.decks.clone();

    // Mirrors the launcher's store precedence, so reset hits the same
    // progress that serving uses.
    let store_path = args
        .store
        .clone()
        .or_else(|| store_path_for(&deck_paths, None))
        .or_else(|| target.default_store.clone())
        .or_else(alix::store::default_store_path)
        .context("cannot determine the data directory")?;
    let (cards, label, _, _) = load_decks(&deck_paths, &HashMap::new())?;

    // A full-deck reset (no `--card` subset) resets authored-card progress,
    // the "mastered" exam flag, and personal cards together atomically: a
    // declined/failed prompt must leave the store untouched by all of it.
    if args.card.is_none() {
        // Load the decks once, up front, for both the confirm-prompt count
        // and the wipe below: loading twice would let a deck edited on disk
        // in between silently diverge (a renamed back line changes
        // `Card::id()`, orphaning the old schedule).
        let decks_full: Vec<Deck> = deck_paths
            .iter()
            .map(Deck::load)
            .collect::<Result<Vec<_>, _>>()?;

        // A full reset discards per-document state, so each TARGET document
        // opens alone and siblings are never parsed: a readable one resets
        // surgically (orphans keep their opt-in-only rule) and an unreadable
        // one is removed after the confirm, because the discard command must
        // not be blocked by the damage it discards.
        let mut readable: Vec<(Store, &Deck)> = Vec::new();
        let mut unreadable: Vec<PathBuf> = Vec::new();
        for (deck_path, deck) in deck_paths.iter().zip(&decks_full) {
            match state::open_store(deck_path, &store_path) {
                Ok(store) => readable.push((store, deck)),
                Err(state::StateError::Store(alix::store::StoreError::Format { path, .. })) => {
                    unreadable.push(path)
                }
                Err(error) => return Err(error.into()),
            }
        }

        fn deck_id(deck: &Deck) -> &str {
            deck.deck_token.as_deref().unwrap_or_default()
        }
        // The prompt must count what reset_decks will actually remove: the
        // deduplicated union of stored live, personal, and dormant ids.
        let mut ids: HashSet<String> = HashSet::new();
        let mut mastered = false;
        for (store, deck) in &readable {
            mastered |= store.deck_mastered(deck_id(deck));
            let deck_ids = deck
                .cards
                .iter()
                .filter_map(Card::id)
                .chain(alix::personal::card_ids(deck))
                .chain(deck.dormant_base_ids());
            for id in deck_ids {
                if store.get(&id).is_some() {
                    ids.insert(id);
                }
            }
        }

        if ids.is_empty() && !mastered && unreadable.is_empty() {
            println!("No stored progress to reset in {label}.");
            return Ok(());
        }

        let n = ids.len();
        let prompt = if unreadable.is_empty() {
            format!("Reset progress for {n} card(s) in {label}?")
        } else {
            format!(
                "Reset progress for {n} card(s) in {label} and remove {} unreadable progress document(s)?",
                unreadable.len()
            )
        };
        if !confirm(&prompt, args.yes)? {
            println!("Cancelled.");
            return Ok(());
        }

        // Removal precedes every readable reset: a removal failure must
        // abort while nothing destructive has committed yet.
        for path in &unreadable {
            std::fs::remove_file(path)
                .with_context(|| format!("cannot remove `{}`", path.display()))?;
        }
        let mut wiped = 0;
        for (mut store, deck) in readable {
            wiped += alix::library::reset_decks(&mut store, std::iter::once(deck))?;
        }
        println!("Reset {wiped} card(s).");
        if !unreadable.is_empty() {
            println!(
                "Removed {} unreadable progress document(s).",
                unreadable.len()
            );
        }
        return Ok(());
    }

    let mut store = state::open_stores(&deck_paths, &store_path)?;
    let targets = select_reset_ids(&cards, args.card.as_deref());
    reset_ids(
        &mut store,
        targets,
        label,
        args.card.as_deref(),
        false,
        args.yes,
    )
}

fn reset_orphans(args: &ResetArgs, config: &Config) -> Result<()> {
    let folder_scope = |dir: &Path| -> Result<(Vec<PathBuf>, PathBuf)> {
        let store = args
            .store
            .clone()
            .unwrap_or_else(|| workspace::root_store_path(dir));
        let found = workspace::classify_deck_files(dir)
            .context("refusing to judge orphans while the target cannot be listed")?;
        Ok((
            found
                .initialized
                .into_iter()
                .chain(found.uninitialized)
                .collect(),
            store,
        ))
    };
    let (deck_paths, store_path) = match &args.target {
        Some(target) if target.is_file() => {
            let decks = vec![target.clone()];
            let store = args
                .store
                .clone()
                .or_else(|| store_path_for(&decks, None))
                .or_else(|| config.decks_dir().map(|d| workspace::root_store_path(&d)))
                .or_else(alix::store::default_store_path)
                .context("cannot determine the data directory")?;
            (decks, store)
        }
        Some(target) if target.is_dir() => folder_scope(target)?,
        Some(target) => bail!("`{}` is neither a deck file nor a folder", target.display()),
        None => folder_scope(&config.decks_dir().context("cannot determine ~/decks")?)?,
    };

    // An unstamped card has no id and no store entry, so it's neither known
    // nor an orphan.
    let mut known_cards: HashSet<String> = HashSet::new();
    let mut known_deck_tokens: HashSet<String> = HashSet::new();
    for path in &deck_paths {
        let deck = Deck::load(path)
            .context("refusing to judge orphans while a deck in the target cannot be read")?;
        known_deck_tokens.extend(deck.deck_token.clone());
        known_cards.extend(deck.cards.iter().filter_map(Card::id));
        known_cards.extend(alix::personal::card_ids(&deck));
        known_cards.extend(deck.dormant_base_ids());
    }

    let mut store = match args.target.as_deref() {
        Some(deck) if deck.is_file() => state::open_store(deck, &store_path)?,
        _ => state::open_aggregate_store(&store_path)?,
    };
    let orphans = store.orphans(&known_cards, &known_deck_tokens);
    if orphans.is_empty() {
        println!("No orphaned progress to reset.");
        return Ok(());
    }
    let n = orphans.len();
    if !confirm(
        &format!("Reset {n} orphaned key(s) (matching no known card or deck)?"),
        args.yes,
    )? {
        println!("Cancelled.");
        return Ok(());
    }
    let removed = store.prune_orphans(&orphans);
    store.save()?;
    println!("Reset {removed} orphaned key(s).");
    Ok(())
}

fn reset_ids(
    store: &mut Store,
    targets: Vec<(String, String)>,
    scope: String,
    card_query: Option<&str>,
    from_picker: bool,
    yes: bool,
) -> Result<()> {
    let present: Vec<(String, String)> = targets
        .into_iter()
        .filter(|(id, _)| store.get(id).is_some())
        .collect();
    if present.is_empty() {
        match card_query {
            Some(query) => println!("No stored progress matching {query:?}."),
            None => println!("No stored progress to reset in {scope}."),
        }
        return Ok(());
    }

    let n = present.len();
    if !from_picker {
        let what = if card_query.is_some() {
            let fronts: Vec<String> = present
                .iter()
                .map(|(_, f)| f.chars().take(60).collect())
                .filter(|f: &String| !f.is_empty())
                .collect();
            if fronts.is_empty() {
                scope
            } else {
                fronts.join("; ")
            }
        } else {
            format!("{n} card(s) in {scope}")
        };
        if !confirm(&format!("Reset progress for {what}?"), yes)? {
            println!("Cancelled.");
            return Ok(());
        }
    }

    for (id, _) in &present {
        store.remove(id);
    }
    store.save()?;
    println!("Reset {n} card(s).");
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;

    fn card(front: &str, back: &str) -> Card {
        let mut c = Card::plain(
            Arc::from("d.md"),
            front.into(),
            vec![back.into()],
            Vec::new(),
            1,
        );
        let slug: String = back
            .chars()
            .filter(|ch| ch.is_ascii_alphanumeric())
            .collect::<String>()
            .to_ascii_lowercase();
        c.token = Some(Arc::from(format!("q{slug}").as_str()));
        c
    }

    #[test]
    fn reset_selects_all_without_a_filter() {
        let cards = vec![card("A", "1"), card("B", "2")];
        assert_eq!(2, select_reset_ids(&cards, None).len());
    }

    #[test]
    fn reset_matches_front_substring_case_insensitively() {
        let cards = vec![
            card("Capital of Japan?", "Tokyo"),
            card("Largest planet?", "Jupiter"),
        ];
        let got = select_reset_ids(&cards, Some("japan"));
        assert_eq!(1, got.len());
        assert_eq!("Capital of Japan?", got[0].1);
    }

    #[test]
    fn reset_matches_a_card_id_exactly() {
        let cards = vec![card("A", "1"), card("B", "2")];
        let id = cards[1].id().unwrap();
        assert_eq!(
            vec![(id.clone(), "B".to_string())],
            select_reset_ids(&cards, Some(&id))
        );
    }

    #[test]
    fn reset_front_match_resets_all_cards_sharing_it() {
        let cards = vec![
            card("verb forms", "a"),
            card("verb forms", "b"),
            card("noun", "c"),
        ];
        let got = select_reset_ids(&cards, Some("verb forms"));
        assert_eq!(2, got.len());
        assert_ne!(got[0].0, got[1].0);
    }
}