alix 0.7.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
use std::path::{Path, PathBuf};

use alix::{config::Config, deck::Deck, generate, library, math, parser};
use anyhow::{Context, Result, bail};

use crate::{
    GenerateArgs,
    common::{confirm, deck_out_dir, preflight_source, store_for},
};

pub(crate) fn generate_cmd(args: GenerateArgs) -> Result<()> {
    let mut config = Config::load(args.config.as_deref())?;
    config.ask.progress = true;
    config.ask.idle_timeout_secs = config.generate.idle_timeout();
    if let Some(url) = &args.source_url
        && !alix::deck::is_url(url)
    {
        bail!("`--source-url` must be an http or https URL");
    }
    let goal = args.goal.as_deref().unwrap_or(generate::DEFAULT_GOAL);
    let mut spec = generate::GenerationSpec::from_config(goal, &config.generate);
    if let Some(language) = args.language.as_deref() {
        let language = language.trim();
        if language.is_empty() {
            bail!("`--language` cannot be empty");
        }
        spec.language = Some(language.to_string());
    }
    if let Some(audience) = args.audience.as_deref() {
        let audience = audience.trim();
        if audience.is_empty() {
            bail!("`--audience` cannot be empty");
        }
        spec.audience = Some(audience.to_string());
    }
    if let Some(style) = args.card_style {
        spec.card_style = style;
    }
    let src_path = PathBuf::from(&args.source);

    if src_path.is_file()
        && src_path.extension().is_some_and(|e| e == "md")
        && std::fs::read_to_string(&src_path).is_ok_and(|t| {
            alix::parser::parse("stub.md", &t).is_ok_and(|d| d.frontmatter.trace.is_some())
        })
    {
        let deck = Deck::load(&src_path)?;
        return trace_build(&src_path, &deck, args.yes, args.force, &config);
    }

    if args.trace {
        if args.plan {
            return trace_suggest(&args.source, args.yes, &config);
        }
        return generate_trace_walk(&args, &config, &spec);
    }

    if src_path.is_dir() && !args.deck {
        let source = canonical_source(&args.source);
        // Confirm before any exploration call, so a decline never spends a
        // paid backend request.
        if !args.plan {
            let staging = staging_dir_for(&workspace_dest(&args, &config, &source)?);
            if !confirm_stale_staging(&staging, args.yes)? {
                println!("Cancelled.");
                return Ok(());
            }
            let _ = std::fs::remove_dir_all(&staging);
        }
        preflight_source(&source, config.ask.preflight_threshold, args.yes)?;
        eprintln!(
            "Exploring {source} for a learning plan toward \"{goal}\" (one pass — \
             this can take a minute)…"
        );
        let plan = alix::explore::explore(&source, &spec, &config.trace, &config.ask)?;
        let items = alix::explore::parse_plan(&plan).len();
        println!("{plan}");
        if args.plan {
            return Ok(());
        }
        if items > 1 {
            return build_workspace(&args, &config, &source, &spec, items);
        }
        eprintln!("The plan has one item; generating a single deck.");
    }
    generate_single_deck(&args, &config, &spec)
}

// Resolved before any backend call so a missing workspace or an existing deck
// fails in milliseconds instead of after a paid generation.
fn resolve_destination(
    args: &GenerateArgs,
    config: &Config,
    name: &str,
) -> Result<(PathBuf, PathBuf)> {
    let dir = deck_out_dir(args.workspace.as_deref(), config)?;
    let target = dir.join(name);
    if target.exists() && !args.force {
        bail!(
            "{} already exists; pass --force to overwrite",
            target.display()
        );
    }
    Ok((dir, target))
}

fn canonical_source(source: &str) -> String {
    let path = Path::new(source);
    if path.exists() {
        std::fs::canonicalize(path)
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| source.to_string())
    } else {
        source.to_string()
    }
}

fn workspace_dest(args: &GenerateArgs, config: &Config, source: &str) -> Result<PathBuf> {
    Ok(match &args.workspace {
        Some(dir) => dir.clone(),
        None => {
            let name = Path::new(source)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("workspace");
            config
                .decks_dir()
                .context("cannot determine the decks directory")?
                .join(name)
        }
    })
}

/// Dot-prefixed so `picker::dir_candidates` skips it: a staging dir kept on
/// a merge conflict never leaks into the picker as a bogus workspace.
fn staging_dir_for(dir: &Path) -> PathBuf {
    let staging_name = format!(
        ".{}.building",
        dir.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("workspace")
    );
    dir.with_file_name(staging_name)
}

fn confirm_stale_staging(staging: &Path, yes: bool) -> Result<bool> {
    let has_files = std::fs::read_dir(staging).is_ok_and(|mut entries| entries.next().is_some());
    if !has_files {
        return Ok(true);
    }
    confirm(
        &format!(
            "{} holds files from a previous build — wipe them and rebuild?",
            staging.display()
        ),
        yes,
    )
}

fn build_workspace(
    args: &GenerateArgs,
    config: &Config,
    source: &str,
    spec: &generate::GenerationSpec,
    items: usize,
) -> Result<()> {
    let dir = workspace_dest(args, config, source)?;
    if !confirm(
        &format!(
            "Build {items} items into {} (several AI calls, a few minutes)?",
            dir.display()
        ),
        args.yes,
    )? {
        println!("Cancelled. `--plan` prints the plan without building.");
        return Ok(());
    }
    eprintln!(
        "Exploring {source} and filling the workspace toward \"{}\" (explore \
         + fill in one session; this can take a few minutes)…",
        spec.goal
    );
    let (plan, filled) = alix::explore::explore_and_fill(source, spec, &config.trace, &config.ask)?;
    println!("{plan}");

    let staging = staging_dir_for(&dir);
    let _ = std::fs::remove_dir_all(&staging);
    let materialized = alix::explore::materialize(
        &plan,
        &staging,
        &spec.goal,
        args.title.as_deref(),
        source,
        args.source_url.as_deref(),
        Some(&filled),
    )?;
    let frozen = alix::explore::freeze_workspace(&staging)?;
    if !frozen.failed.is_empty() {
        bail!(
            "the generated workspace was not published because its evidence could not be frozen:\n{}",
            frozen.failed.join("\n")
        );
    }
    let existing_decks = alix::workspace::deck_files(&dir);
    let mut store = store_for(&existing_decks, None, config)
        .with_context(|| format!("opening the store for {}", dir.display()))?;
    let merged = alix::explore::merge_built(&staging, &dir, args.force, &mut store)?;

    let total = materialized.traces + materialized.decks;
    let stubs = total - materialized.filled;
    println!(
        "\n{BOLD}Built {total} files{RESET} in {} — {} filled, {stubs} stub(s) \
         ({} traces, {} decks).",
        dir.display(),
        materialized.filled,
        materialized.traces,
        materialized.decks,
    );
    if merged.conflicts.is_empty() {
        let _ = std::fs::remove_dir_all(&staging);
    } else {
        for name in &merged.conflicts {
            eprintln!(
                "kept yours: {name} — the new version is at {}/{name}",
                staging.display()
            );
        }
        eprintln!("re-run with --force to overwrite, or move them in by hand.");
    }
    if frozen.files > 0 {
        println!(
            "{DIM}Froze {} source and image asset(s) for {} deck(s) into {}/assets.{RESET}",
            frozen.files,
            frozen.decks,
            dir.display(),
        );
    }
    match args.icon.as_deref() {
        Some(src) => match alix::icon::install(&dir, src) {
            Ok(_) => println!(
                "{DIM}Installed the workspace icon into {}/assets.{RESET}",
                dir.display()
            ),
            Err(e) => eprintln!("warning: could not install the workspace icon: {e:#}"),
        },
        None => match alix::icon::generate(&dir, None, &config.ask) {
            Ok(_) => println!(
                "{DIM}Drew a workspace icon into {}/assets.{RESET}",
                dir.display()
            ),
            Err(e) => eprintln!("warning: could not draw a workspace icon: {e:#}"),
        },
    }
    println!("{DIM}Open it:  alix {}{RESET}", dir.display());
    Ok(())
}

fn generate_single_deck(
    args: &GenerateArgs,
    config: &Config,
    spec: &generate::GenerationSpec,
) -> Result<()> {
    let mut gen_cfg = config.generate.clone();
    if let Some(cards) = args.cards {
        gen_cfg.max_cards = cards;
    }

    let source = if std::path::Path::new(&args.source).exists() {
        std::fs::canonicalize(&args.source)
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| args.source.clone())
    } else {
        args.source.clone()
    };

    let name = match &args.output {
        Some(name) => name.clone(),
        None => generate::deck_name(&source),
    };
    let name = if name.ends_with(".md") {
        name
    } else {
        format!("{name}.md")
    };
    let destination = if args.print {
        None
    } else {
        Some(resolve_destination(args, config, &name)?)
    };

    preflight_source(&source, config.ask.preflight_threshold, args.yes)?;
    eprintln!("Generating a deck from {source} (this can take a minute)…");
    let mut text = generate::generate_deck(&source, &gen_cfg, &config.ask, spec)?;
    if let Some(url) = &args.source_url {
        text = alix::deck::with_added_source(&text, url)?;
    }

    if args.review || gen_cfg.review {
        eprintln!("Reviewing the deck to remove redundant cards…");
        text = generate::review_deck(&text, &gen_cfg, &config.ask, spec)?;
    }

    // Parse against the final name (part of every card's id hash); a parse
    // error still saves the output rather than losing the generation.
    let parsed = parser::parse(&name, &text);

    if args.print {
        print!("{text}");
        if !text.ends_with('\n') {
            println!();
        }
        match parser::parse_str(&name, &text) {
            Ok(cards) => eprintln!("({} cards, not written; --print)", cards.len()),
            Err(e) => eprintln!("(warning: does not parse yet: {e})"),
        }
        if let Ok(deck) = &parsed
            && let Err(diagnostic) = math::validate_generated(&deck.cards)
        {
            eprintln!("(warning: generated deck has invalid LaTeX math: {diagnostic})");
        }
        return Ok(());
    }

    if let Ok(deck) = &parsed
        && let Err(diagnostic) = math::validate_generated(&deck.cards)
    {
        bail!("generated deck `{name}` has invalid LaTeX math: {diagnostic}");
    }

    let (dir, target) = destination.expect("resolved above unless --print returned early");
    if target.exists() {
        let mut store = store_for(std::slice::from_ref(&target), None, config)?;
        let report = library::replace_deck(&dir, &name, &text, &mut store)?;
        if Path::new(&source).exists() {
            alix::source::stamp_citations(&target)?;
        }
        println!(
            "Replaced {}: {} cards, wiped progress for {} card(s).",
            target.display(),
            report.minted,
            report.wiped_cards
        );
        return Ok(());
    }
    let placed = library::place_deck(&dir, &name, &text)?;
    match placed.parse_error {
        None => {
            if Path::new(&source).exists() {
                alix::source::stamp_citations(&placed.path)?;
            }
            println!("Wrote {} cards to {}", placed.cards, placed.path.display());
            Ok(())
        }
        Some(e) => bail!(
            "Saved the generated deck to {}, but it does not parse yet:\n  {e}\n\
             Fix that line and run `alix doctor {}`.",
            placed.path.display(),
            placed.path.display()
        ),
    }
}

const BOLD: &str = "\x1b[1m";
const DIM: &str = "\x1b[2m";
const RESET: &str = "\x1b[0m";

fn trace_build(
    deck_path: &Path,
    deck: &Deck,
    yes: bool,
    force: bool,
    config: &Config,
) -> Result<()> {
    if !deck.is_trace() {
        bail!(
            "{} declares no `trace:` — add the path you want to understand \
             (e.g. a frontmatter `trace: how X becomes Y`), then build it",
            deck.subject
        );
    }
    if deck.sources.is_empty() {
        bail!(
            "{} declares no `source:` — add the scope to trace (a repo `.`, a \
             directory, a file, or a URL)",
            deck.subject
        );
    }
    let rebuild = !deck.cards.is_empty();
    if rebuild && !force {
        bail!(
            "{} already has checkpoints; pass --force to rebuild (this wipes their progress)",
            deck.subject
        );
    }
    let source = deck.sources.first().map(String::as_str).unwrap_or_default();
    preflight_source(source, config.ask.preflight_threshold, yes)?;
    eprintln!(
        "Tracing a path through {source} (exploring the source — this can take a \
         few minutes)…"
    );
    let cards = alix::trace_ai::build(deck, &config.trace, &config.ask)?;

    if rebuild {
        let existing = std::fs::read_to_string(deck_path)
            .with_context(|| format!("cannot read {}", deck_path.display()))?;
        let new_text = alix::deck::trace_checkpoint_text(deck_path, &existing, &cards)?;
        let dir = deck_path.parent().unwrap_or_else(|| Path::new("."));
        let name = deck_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("trace.md");
        let mut store = store_for(std::slice::from_ref(&deck_path.to_path_buf()), None, config)?;
        let report = library::replace_deck(dir, name, &new_text, &mut store)?;
        println!(
            "Rebuilt {}: {} checkpoints, wiped progress for {} card(s). Review them \
             and their `at:` locators, then walk it from the picker.",
            deck_path.display(),
            report.minted,
            report.wiped_cards
        );
        return Ok(());
    }

    alix::deck::set_trace_checkpoints(deck_path, &cards)?;
    let initialized = alix::assets::initialize(deck_path)?;
    if initialized.freeze.is_none() {
        alix::source::stamp_citations(deck_path)?;
    }

    let n = alix::parser::parse_str(&deck.subject, &cards)
        .map(|c| c.len())
        .unwrap_or(0);
    println!(
        "Wrote {n} checkpoints to {}. Review them and their `at:` locators, \
         then walk it from the picker: run `alix` and pick it.",
        deck_path.display()
    );
    Ok(())
}

fn trace_suggest(source: &str, yes: bool, config: &Config) -> Result<()> {
    preflight_source(source, config.ask.preflight_threshold, yes)?;
    eprintln!(
        "Reconning {source} for traces worth tracing (one exploration pass — this \
         can take a minute)…"
    );
    let menu = alix::trace_ai::suggest(source, &config.trace, &config.ask)?;
    println!("{menu}");
    println!(
        "\n{DIM}Paste a suggestion into a new deck's frontmatter (its `trace:` + \
         `source:` keys), then build it:  alix generate <deck>{RESET}"
    );
    Ok(())
}

fn generate_trace_walk(
    args: &GenerateArgs,
    config: &Config,
    spec: &generate::GenerationSpec,
) -> Result<()> {
    let source = canonical_source(&args.source);
    let dir = deck_out_dir(args.workspace.as_deref(), config)?;
    let raw = PathBuf::from(args.output.clone().unwrap_or_else(|| "explore.md".into()));
    let out = if args.workspace.is_some() {
        dir.join(&raw)
    } else {
        raw
    };
    if out.exists() && !args.force {
        bail!(
            "{} already exists; pass --force to overwrite",
            out.display()
        );
    }

    preflight_source(&source, config.ask.preflight_threshold, args.yes)?;
    eprintln!(
        "Exploring {source} to build an explore walk (one pass — this can take a \
         minute)…"
    );
    let checkpoints = alix::explore::walk(&source, spec, &config.trace, &config.ask)?;

    let name = Path::new(&source)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(source.as_str());
    // Quote through the L1 quoter: a name/source with `"`/`\` or `:` would
    // otherwise break the YAML mapping.
    let trace = parser::yaml_quote(&format!(
        "exploring {name} — what it is, its parts, and its spine"
    ));
    let mut deck_text = format!(
        "---\ntrace: {trace}\nsource: {}\n\n---\n\n{checkpoints}\n",
        parser::yaml_quote(&source)
    );
    if let Some(url) = &args.source_url {
        deck_text = alix::deck::with_added_source(&deck_text, url)?;
    }
    let out_dir = out
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));
    let name = out
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("explore.md")
        .to_string();
    if out.exists() {
        let mut store = store_for(std::slice::from_ref(&out), None, config)?;
        let report = library::replace_deck(&out_dir, &name, &deck_text, &mut store)?;
        println!(
            "Rebuilt the explore walk at {}: {} checkpoints, wiped progress for {} card(s).",
            out.display(),
            report.minted,
            report.wiped_cards
        );
        return Ok(());
    }
    let placed = library::place_deck(&out_dir, &name, &deck_text)?;
    if let Some(e) = &placed.parse_error {
        eprintln!("warning: the explore walk does not parse yet: {e}");
    }
    println!(
        "Wrote the explore walk to {} — walk it from the picker: run `alix` and \
         pick it.",
        placed.path.display()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    fn generate_args(force: bool) -> GenerateArgs {
        GenerateArgs {
            source: "notes.md".to_string(),
            source_url: None,
            goal: None,
            language: None,
            audience: None,
            card_style: None,
            plan: false,
            trace: false,
            deck: false,
            workspace: None,
            output: None,
            cards: None,
            review: false,
            print: false,
            force,
            title: None,
            icon: None,
            yes: false,
            config: None,
        }
    }

    #[test]
    fn a_fresh_destination_resolves_and_an_existing_one_demands_force() {
        let dir = TempDir::new().unwrap();
        let config = Config {
            decks_dir: Some(dir.path().to_path_buf()),
            ..Config::default()
        };

        let (out_dir, target) =
            resolve_destination(&generate_args(false), &config, "d.md").unwrap();
        assert_eq!(dir.path(), out_dir, "the decks dir is the destination");
        assert_eq!(dir.path().join("d.md"), target);

        std::fs::write(&target, "existing deck").unwrap();
        let err = resolve_destination(&generate_args(false), &config, "d.md").unwrap_err();
        assert!(
            format!("{err:#}").contains("already exists"),
            "an existing target without --force must refuse: {err:#}"
        );

        assert!(
            resolve_destination(&generate_args(true), &config, "d.md").is_ok(),
            "--force must allow overwriting the existing target"
        );
    }
}