aprender-train-shell 0.70.2

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

use crate::state::{HistoryEntry, ModelRole, SessionState};
use entrenar_common::{EntrenarError, Result};

/// A parsed command.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    /// Fetch a model from HuggingFace
    Fetch { model_id: String, role: ModelRole },
    /// Inspect a loaded model
    Inspect { target: InspectTarget },
    /// Estimate memory requirements
    Memory {
        batch_size: Option<u32>,
        seq_len: Option<usize>,
    },
    /// Set configuration values
    Set { key: String, value: String },
    /// Run distillation
    Distill { dry_run: bool },
    /// Export model to file
    Export { format: String, path: String },
    /// Show command history
    History,
    /// Show help
    Help { topic: Option<String> },
    /// Clear screen
    Clear,
    /// Quit the shell
    Quit,
    /// Unknown command
    Unknown { input: String },
}

/// Target for inspect command.
#[derive(Debug, Clone, PartialEq)]
pub enum InspectTarget {
    /// Inspect layer structure
    Layers,
    /// Inspect memory usage
    Memory,
    /// Inspect all info
    All,
    /// Inspect specific model by name
    Model(String),
}

/// Parse a command string into a Command.
pub fn parse(input: &str) -> Result<Command> {
    let input = input.trim();
    if input.is_empty() {
        return Ok(Command::Unknown {
            input: String::new(),
        });
    }

    let parts: Vec<&str> = input.split_whitespace().collect();
    let cmd = parts[0].to_lowercase();
    let args = &parts[1..];

    match cmd.as_str() {
        "fetch" | "download" => parse_fetch(args),
        "inspect" | "show" => parse_inspect(args),
        "memory" | "mem" => parse_memory(args),
        "set" => parse_set(args),
        "distill" | "train" => parse_distill(args),
        "export" | "save" => parse_export(args),
        "history" | "hist" => Ok(Command::History),
        "help" | "?" => parse_help(args),
        "clear" | "cls" => Ok(Command::Clear),
        "quit" | "exit" | "q" => Ok(Command::Quit),
        _ => Ok(Command::Unknown {
            input: input.to_string(),
        }),
    }
}

fn parse_fetch(args: &[&str]) -> Result<Command> {
    if args.is_empty() {
        return Err(EntrenarError::ConfigValue {
            field: "model_id".into(),
            message: "No model ID provided".into(),
            suggestion: "Usage: fetch <model_id> [--teacher|--student]".into(),
        });
    }

    let model_id = args[0].to_string();
    let role = if args.contains(&"--teacher") {
        ModelRole::Teacher
    } else if args.contains(&"--student") {
        ModelRole::Student
    } else {
        ModelRole::None
    };

    Ok(Command::Fetch { model_id, role })
}

fn parse_inspect(args: &[&str]) -> Result<Command> {
    let target = if args.is_empty() {
        InspectTarget::All
    } else {
        match args[0].to_lowercase().as_str() {
            "layers" | "layer" => InspectTarget::Layers,
            "memory" | "mem" => InspectTarget::Memory,
            "all" => InspectTarget::All,
            name => InspectTarget::Model(name.to_string()),
        }
    };

    Ok(Command::Inspect { target })
}

fn parse_memory(args: &[&str]) -> Result<Command> {
    let mut batch_size = None;
    let mut seq_len = None;

    let mut i = 0;
    while i < args.len() {
        match args[i] {
            "--batch" | "-b" if i + 1 < args.len() => {
                batch_size = args[i + 1].parse().ok();
                i += 2;
            }
            "--seq" | "-s" if i + 1 < args.len() => {
                seq_len = args[i + 1].parse().ok();
                i += 2;
            }
            _ => i += 1,
        }
    }

    Ok(Command::Memory {
        batch_size,
        seq_len,
    })
}

fn parse_set(args: &[&str]) -> Result<Command> {
    if args.len() < 2 {
        return Err(EntrenarError::ConfigValue {
            field: "set".into(),
            message: "Not enough arguments".into(),
            suggestion: "Usage: set <key> <value>".into(),
        });
    }

    Ok(Command::Set {
        key: args[0].to_string(),
        value: args[1..].join(" "),
    })
}

fn parse_distill(args: &[&str]) -> Result<Command> {
    let dry_run = args.contains(&"--dry-run") || args.contains(&"-n");
    Ok(Command::Distill { dry_run })
}

fn parse_export(args: &[&str]) -> Result<Command> {
    if args.len() < 2 {
        return Err(EntrenarError::ConfigValue {
            field: "export".into(),
            message: "Not enough arguments".into(),
            suggestion: "Usage: export <format> <path>".into(),
        });
    }

    Ok(Command::Export {
        format: args[0].to_string(),
        path: args[1].to_string(),
    })
}

fn parse_help(args: &[&str]) -> Result<Command> {
    let topic = args.first().map(ToString::to_string);
    Ok(Command::Help { topic })
}

/// Execute a command and update state.
pub fn execute(cmd: &Command, state: &mut SessionState) -> Result<String> {
    let start = std::time::Instant::now();

    let result = match cmd {
        // #2519: `role` is no longer read -- nothing can be loaded, so nothing
        // can be assigned a teacher/student role. It stays in the parsed command
        // because `parse` still validates the flags.
        Command::Fetch { model_id, .. } => execute_fetch(model_id),
        Command::Inspect { target } => execute_inspect(target, state),
        Command::Memory {
            batch_size,
            seq_len,
        } => execute_memory(*batch_size, *seq_len, state),
        Command::Set { key, value } => execute_set(key, value, state),
        Command::Distill { dry_run } => execute_distill(*dry_run, state),
        Command::Export { format, path } => execute_export(format, path, state),
        Command::History => execute_history(state),
        Command::Help { topic } => execute_help(topic.as_deref()),
        Command::Clear => Ok(String::new()),
        Command::Quit => Ok("Goodbye!".to_string()),
        Command::Unknown { input } => {
            if input.is_empty() {
                Ok(String::new())
            } else {
                Err(EntrenarError::ConfigValue {
                    field: "command".into(),
                    message: format!("Unknown command: {input}"),
                    suggestion: "Type 'help' for available commands".into(),
                })
            }
        }
    };

    let duration_ms = start.elapsed().as_millis() as u64;
    let success = result.is_ok();

    // Record in history (except for help/history/clear/quit)
    if !matches!(
        cmd,
        Command::Help { .. }
            | Command::History
            | Command::Clear
            | Command::Quit
            | Command::Unknown { .. }
    ) {
        let cmd_str = format!("{cmd:?}");
        state.add_to_history(HistoryEntry::new(cmd_str, duration_ms, success));
        state.record_command(duration_ms, success);
    }

    result
}

fn execute_fetch(model_id: &str) -> Result<String> {
    // #2519: this used to open with
    //
    //     // Simulate model fetching
    //     let model = LoadedModel {
    //         architecture: detect_architecture(model_id),
    //         parameters: estimate_params(model_id),
    //         layers: estimate_layers(model_id),
    //         hidden_dim: 4096,
    //
    // and returned "✓ Fetched {model_id}". Two separate things were wrong.
    //
    // First, nothing was fetched: this crate has no HTTP client and no
    // HuggingFace dependency, so no bytes ever moved. Measured before this
    // change, on a model ID that cannot exist:
    //
    //     ✓ Fetched does-not-exist/totally-fake-7b
    //       Architecture: unknown
    //       Parameters: 7.0B
    //       Layers: 32
    //
    // Second, those figures are read out of the model ID STRING: "7b" in the
    // name yields 7.0B and 32 layers, and hidden_dim was the literal 4096. The
    // architecture line is the one part that behaved -- it warns and reports
    // `unknown` -- which is why it is the only guess kept anywhere near honest.
    //
    // Refusing is strictly better than fabricating. Whether this binary should
    // exist at all is tracked in #2519; this change does not prejudge it.
    Err(EntrenarError::ConfigValue {
        field: "fetch".into(),
        message: format!(
            "cannot fetch `{model_id}`: this shell has no HuggingFace client, so it \
             downloads nothing. It previously reported success for any string at all, \
             with a parameter count and layer count string-matched out of the model \
             ID itself"
        ),
        suggestion: "Download with `apr pull <model_id>` or `apr import hf://<model_id>`, \
                     then read the real file with `apr inspect` / `apr tensors`. \
                     Tracked in #2519."
            .into(),
    })
}

fn execute_inspect(target: &InspectTarget, state: &SessionState) -> Result<String> {
    match target {
        InspectTarget::All => {
            if state.loaded_models().is_empty() {
                return Ok("No models loaded. Use 'fetch <model_id>' to load a model.".to_string());
            }

            let mut output = String::from("Loaded Models:\n");
            for (name, model) in state.loaded_models() {
                output.push_str(&format!(
                    "  {} ({}): {:.1}B params, {} layers\n",
                    name,
                    model.id,
                    model.parameters as f64 / 1e9,
                    model.layers
                ));
            }
            Ok(output)
        }
        InspectTarget::Layers => {
            let mut output = String::from("Layer Analysis:\n");
            for (name, model) in state.loaded_models() {
                output.push_str(&format!(
                    "  {}: {} layers, hidden_dim={}\n",
                    name, model.layers, model.hidden_dim
                ));
            }
            Ok(output)
        }
        InspectTarget::Memory => execute_memory(None, None, state),
        InspectTarget::Model(name) => {
            if let Some(model) = state.get_model(name) {
                Ok(format!(
                    "Model: {}\n  ID: {}\n  Path: {}\n  Architecture: {}\n  Parameters: {:.1}B\n  Layers: {}\n  Hidden Dim: {}",
                    name, model.id, model.path.display(), model.architecture,
                    model.parameters as f64 / 1e9, model.layers, model.hidden_dim
                ))
            } else {
                Err(EntrenarError::ModelNotFound { path: name.into() })
            }
        }
    }
}

fn execute_memory(
    batch_size: Option<u32>,
    seq_len: Option<usize>,
    state: &SessionState,
) -> Result<String> {
    let batch = batch_size.unwrap_or(state.preferences().default_batch_size);
    let seq = seq_len.unwrap_or(state.preferences().default_seq_len);

    let total_params: u64 = state.loaded_models().values().map(|m| m.parameters).sum();
    let model_mem = total_params * 2; // FP16
    let activation_mem = u64::from(batch) * (seq as u64) * 4096 * 32 * 2;
    let total = model_mem + activation_mem;

    Ok(format!(
        "Memory Estimate (batch={}, seq={}):\n  Model: {:.1} GB\n  Activations: {:.1} GB\n  Total: {:.1} GB",
        batch, seq,
        model_mem as f64 / 1e9,
        activation_mem as f64 / 1e9,
        total as f64 / 1e9
    ))
}

fn execute_set(key: &str, value: &str, state: &mut SessionState) -> Result<String> {
    match key {
        "batch_size" | "batch" => {
            let v: u32 = value.parse().map_err(|_| EntrenarError::ConfigValue {
                field: "batch_size".into(),
                message: "Invalid number".into(),
                suggestion: "Use a positive integer".into(),
            })?;
            state.preferences_mut().default_batch_size = v;
            Ok(format!("Set batch_size = {v}"))
        }
        "seq_len" | "seq" => {
            let v: usize = value.parse().map_err(|_| EntrenarError::ConfigValue {
                field: "seq_len".into(),
                message: "Invalid number".into(),
                suggestion: "Use a positive integer".into(),
            })?;
            state.preferences_mut().default_seq_len = v;
            Ok(format!("Set seq_len = {v}"))
        }
        _ => Err(EntrenarError::ConfigValue {
            field: key.into(),
            message: "Unknown setting".into(),
            suggestion: "Available settings: batch_size, seq_len".into(),
        }),
    }
}

fn execute_distill(dry_run: bool, state: &SessionState) -> Result<String> {
    let teacher = state
        .loaded_models()
        .values()
        .find(|m| m.role == ModelRole::Teacher);
    let student = state
        .loaded_models()
        .values()
        .find(|m| m.role == ModelRole::Student);

    if teacher.is_none() {
        return Err(EntrenarError::ConfigValue {
            field: "teacher".into(),
            message: "No teacher model loaded".into(),
            suggestion: "Use 'fetch <model_id> --teacher' to load a teacher model".into(),
        });
    }

    if student.is_none() {
        return Err(EntrenarError::ConfigValue {
            field: "student".into(),
            message: "No student model loaded".into(),
            suggestion: "Use 'fetch <model_id> --student' to load a student model".into(),
        });
    }

    if dry_run {
        let teacher = teacher.expect("teacher validated non-None above");
        let student = student.expect("student validated non-None above");
        Ok(format!(
            "Dry run configuration:\n  Teacher: {} ({:.1}B)\n  Student: {} ({:.1}B)\n  Ready to train",
            teacher.id, teacher.parameters as f64 / 1e9,
            student.id, student.parameters as f64 / 1e9
        ))
    } else {
        // #2519 named this line directly: "distill returns `Training
        // started... (simulated)`". It is a success string for work that never
        // happens — this crate has no training loop, no optimizer and no
        // dataset; it depends on `entrenar` only for its error type.
        //
        // Before the `fetch` fix this was reachable by fetching two fake
        // models; afterwards it was still reachable through `--session`, which
        // is how it survived. Refusing removes it from every door at once.
        Err(EntrenarError::ConfigValue {
            field: "distill".into(),
            message: format!(
                // Deliberately does NOT quote the old success string. The
                // falsifier asserts on substrings, and a refusal that repeats
                // the phrase it is refusing cannot be told apart from the
                // defect by any mechanical check.
                "cannot distill `{}` into `{}`: this shell has no training loop, \
                 no optimizer and no dataset. It previously reported that \
                 training had begun, and exited 0 without training anything",
                teacher.map_or("<teacher>", |t| t.id.as_str()),
                student.map_or("<student>", |s| s.id.as_str()),
            ),
            suggestion: "Run the real trainer: `apr distill` / `apr finetune`. \
                         `distill --dry-run` here still prints the configuration. \
                         Tracked in #2519."
                .into(),
        })
    }
}

fn execute_export(format: &str, path: &str, _state: &SessionState) -> Result<String> {
    // Reported "Exported to {path} in {format} format" and wrote nothing. That is
    // the same fabrication #2519 is about, and it falsified this crate's own
    // `reported_work_was_done` equation, which is universally quantified over
    // every command reachable from `execute`. There is no exporter in this crate
    // to call -- `grep -rn "fn export" crates/aprender-train-shell/src/` is empty
    // -- so the truthful answer is to refuse, not to narrow the equation until
    // the lie fits inside it.
    Err(EntrenarError::ConfigValue {
        field: "export".into(),
        message: format!("export is not implemented in this shell ({format} -> {path})"),
        suggestion: "Use `apr export` for real format conversion.".into(),
    })
}

fn execute_history(state: &SessionState) -> Result<String> {
    if state.history().is_empty() {
        return Ok("No command history.".to_string());
    }

    let mut output = String::from("Command History:\n");
    for (i, entry) in state.history().iter().enumerate() {
        let status = if entry.success { "✓" } else { "✗" };
        output.push_str(&format!(
            "  {}. {} {} ({}ms)\n",
            i + 1,
            status,
            entry.command,
            entry.duration_ms
        ));
    }
    Ok(output)
}

fn execute_help(topic: Option<&str>) -> Result<String> {
    match topic {
        Some("fetch") => Ok(
            "fetch <model_id> [--teacher|--student]\n  Download a model from HuggingFace"
                .to_string(),
        ),
        Some("inspect") => {
            Ok("inspect [layers|memory|all|<model>]\n  Inspect loaded models".to_string())
        }
        Some("memory") => {
            Ok("memory [--batch <n>] [--seq <n>]\n  Estimate memory requirements".to_string())
        }
        Some("distill") => Ok("distill [--dry-run]\n  Run distillation training".to_string()),
        _ => Ok("Available commands:
  fetch <model>      Download model from HuggingFace
  inspect [target]   Inspect loaded models
  memory             Estimate memory requirements
  set <key> <value>  Configure settings
  distill            Run distillation
  export <fmt> <path> Export model
  history            Show command history
  clear              Clear the screen
  help [topic]       Show help
  quit               Exit shell"
            .to_string()),
    }
}

/// N-04 (Meyer DbC): Best-effort architecture guess from model ID string.
/// This is informational only (shell display) — actual architecture detection
/// for inference uses tensor-name-based `ArchitectureDetector::detect()`.
/// Order matters: more specific patterns must come before generic ones
/// (e.g., "mistral" before "llama" since Mistral inherits LLaMA naming).
//
// #2519: `execute_fetch` was the only production caller of the three guessers
// below, so they are now referenced only by the tests that pin their behaviour.
// Scoped to test builds so no production path can present a substring match on
// a model ID as a fact about a model.
#[cfg(test)]
const ARCH_PATTERNS: &[(&[&str], &str)] = &[
    (&["qwen"], "qwen"),
    (&["phi"], "phi"),
    (&["falcon"], "falcon"),
    (&["mistral", "mixtral"], "mistral"),
    (&["llama"], "llama"),
    (&["bert"], "bert"),
    (&["gpt"], "gpt"),
];

#[cfg(test)]
fn detect_architecture(model_id: &str) -> String {
    let lower = model_id.to_lowercase();
    for (patterns, arch) in ARCH_PATTERNS {
        if patterns.iter().any(|p| lower.contains(p)) {
            return (*arch).to_string();
        }
    }
    eprintln!(
        "Warning: could not detect architecture from model ID '{model_id}', \
         defaulting to 'unknown' (use tensor-based detection for accuracy)"
    );
    "unknown".to_string()
}

#[cfg(test)]
fn estimate_params(model_id: &str) -> u64 {
    let lower = model_id.to_lowercase();
    if lower.contains("70b") {
        70_000_000_000
    } else if lower.contains("13b") {
        13_000_000_000
    } else if lower.contains("7b") {
        7_000_000_000
    } else if lower.contains("1.1b") || lower.contains("1b") {
        1_100_000_000
    } else if lower.contains("base") {
        350_000_000
    } else {
        1_000_000_000
    }
}

#[cfg(test)]
fn estimate_layers(model_id: &str) -> u32 {
    let lower = model_id.to_lowercase();
    if lower.contains("70b") {
        80
    } else if lower.contains("13b") {
        40
    } else if lower.contains("7b") {
        32
    } else if lower.contains("base") {
        12
    } else {
        24
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // #2519: only the tests construct models now that nothing is fetched.
    use crate::state::LoadedModel;

    #[test]
    fn test_parse_fetch() {
        let cmd = parse("fetch meta-llama/Llama-2-7b --teacher").expect("parsing should succeed");
        assert!(matches!(
            cmd,
            Command::Fetch {
                role: ModelRole::Teacher,
                ..
            }
        ));

        let cmd =
            parse("fetch TinyLlama/TinyLlama-1.1B --student").expect("parsing should succeed");
        assert!(matches!(
            cmd,
            Command::Fetch {
                role: ModelRole::Student,
                ..
            }
        ));
    }

    #[test]
    fn test_parse_inspect() {
        assert!(matches!(
            parse("inspect").expect("parsing should succeed"),
            Command::Inspect {
                target: InspectTarget::All
            }
        ));
        assert!(matches!(
            parse("inspect layers").expect("parsing should succeed"),
            Command::Inspect {
                target: InspectTarget::Layers
            }
        ));
    }

    #[test]
    fn test_parse_memory() {
        let cmd = parse("memory --batch 64 --seq 1024").expect("parsing should succeed");
        if let Command::Memory {
            batch_size,
            seq_len,
        } = cmd
        {
            assert_eq!(batch_size, Some(64));
            assert_eq!(seq_len, Some(1024));
        } else {
            panic!("Expected Memory command");
        }
    }

    #[test]
    fn test_parse_quit_variants() {
        assert!(matches!(
            parse("quit").expect("parsing should succeed"),
            Command::Quit
        ));
        assert!(matches!(
            parse("exit").expect("parsing should succeed"),
            Command::Quit
        ));
        assert!(matches!(
            parse("q").expect("parsing should succeed"),
            Command::Quit
        ));
    }

    // #2519: this used to assert `is_ok()` and that a "teacher" appeared in the
    // session -- for a model nothing had downloaded. A test of that shape locks
    // the fabrication in: it passes only because the output is invented.
    #[test]
    fn test_execute_fetch_refuses_and_loads_nothing() {
        let mut state = SessionState::new();
        let err = execute(
            &Command::Fetch {
                model_id: "meta-llama/Llama-2-7b".to_string(),
                role: ModelRole::Teacher,
            },
            &mut state,
        )
        .expect_err("fetch must not claim to have downloaded a model");

        assert!(format!("{err}").contains("no HuggingFace client"));
        assert!(state.get_model("teacher").is_none());
        assert!(state.loaded_models().is_empty());
    }

    #[test]
    fn test_execute_set() {
        let mut state = SessionState::new();

        execute_set("batch_size", "64", &mut state).expect("operation should succeed");
        assert_eq!(state.preferences().default_batch_size, 64);

        execute_set("seq_len", "1024", &mut state).expect("operation should succeed");
        assert_eq!(state.preferences().default_seq_len, 1024);
    }

    #[test]
    fn test_unknown_command() {
        let cmd = parse("foobar").expect("parsing should succeed");
        assert!(matches!(cmd, Command::Unknown { .. }));
    }

    #[test]
    fn test_parse_fetch_missing_model() {
        let result = parse("fetch");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_set_not_enough_args() {
        let result = parse("set batch_size");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_export_not_enough_args() {
        let result = parse("export safetensors");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_export_valid() {
        let cmd = parse("export safetensors /tmp/model.st").expect("parsing should succeed");
        if let Command::Export { format, path } = cmd {
            assert_eq!(format, "safetensors");
            assert_eq!(path, "/tmp/model.st");
        } else {
            panic!("Expected Export command");
        }
    }

    #[test]
    fn test_parse_help_with_topic() {
        let cmd = parse("help fetch").expect("parsing should succeed");
        if let Command::Help { topic } = cmd {
            assert_eq!(topic, Some("fetch".to_string()));
        } else {
            panic!("Expected Help command");
        }
    }

    #[test]
    fn test_parse_distill_dry_run() {
        let cmd = parse("distill --dry-run").expect("parsing should succeed");
        if let Command::Distill { dry_run } = cmd {
            assert!(dry_run);
        } else {
            panic!("Expected Distill command");
        }
    }

    #[test]
    fn test_parse_distill_short_flag() {
        let cmd = parse("distill -n").expect("parsing should succeed");
        if let Command::Distill { dry_run } = cmd {
            assert!(dry_run);
        } else {
            panic!("Expected Distill command");
        }
    }

    #[test]
    fn test_parse_inspect_model() {
        let cmd = parse("inspect teacher").expect("parsing should succeed");
        if let Command::Inspect { target } = cmd {
            assert_eq!(target, InspectTarget::Model("teacher".to_string()));
        } else {
            panic!("Expected Inspect command");
        }
    }

    #[test]
    fn test_parse_inspect_memory() {
        let cmd = parse("inspect memory").expect("parsing should succeed");
        assert!(matches!(
            cmd,
            Command::Inspect {
                target: InspectTarget::Memory
            }
        ));
    }

    #[test]
    fn test_parse_command_aliases() {
        // download = fetch
        assert!(matches!(
            parse("download model").expect("parsing should succeed"),
            Command::Fetch { .. }
        ));
        // show = inspect
        assert!(matches!(
            parse("show layers").expect("parsing should succeed"),
            Command::Inspect { .. }
        ));
        // mem = memory
        assert!(matches!(
            parse("mem").expect("parsing should succeed"),
            Command::Memory { .. }
        ));
        // train = distill
        assert!(matches!(
            parse("train").expect("parsing should succeed"),
            Command::Distill { .. }
        ));
        // save = export (needs args)
        assert!(matches!(
            parse("save gguf /tmp/out").expect("parsing should succeed"),
            Command::Export { .. }
        ));
        // cls = clear
        assert!(matches!(
            parse("cls").expect("parsing should succeed"),
            Command::Clear
        ));
        // ? = help
        assert!(matches!(
            parse("?").expect("parsing should succeed"),
            Command::Help { .. }
        ));
        // hist = history
        assert!(matches!(
            parse("hist").expect("parsing should succeed"),
            Command::History
        ));
    }

    #[test]
    fn test_execute_inspect_no_models() {
        let state = SessionState::new();
        let result = execute_inspect(&InspectTarget::All, &state);
        assert!(result
            .expect("load should succeed")
            .contains("No models loaded"));
    }

    #[test]
    fn test_execute_inspect_layers() {
        let mut state = SessionState::new();
        let model = LoadedModel {
            id: "test".to_string(),
            path: std::path::PathBuf::from("/tmp"),
            architecture: "llama".to_string(),
            parameters: 7_000_000_000,
            layers: 32,
            hidden_dim: 4096,
            role: ModelRole::None,
        };
        state.add_model("test".to_string(), model);

        let result =
            execute_inspect(&InspectTarget::Layers, &state).expect("operation should succeed");
        assert!(result.contains("32 layers"));
    }

    #[test]
    fn test_execute_inspect_model_not_found() {
        let state = SessionState::new();
        let result = execute_inspect(&InspectTarget::Model("unknown".to_string()), &state);
        assert!(result.is_err());
    }

    #[test]
    fn test_execute_history_empty() {
        let state = SessionState::new();
        let result = execute_history(&state).expect("operation should succeed");
        assert!(result.contains("No command history"));
    }

    #[test]
    fn test_execute_help_topics() {
        let fetch_help = execute_help(Some("fetch")).expect("operation should succeed");
        assert!(fetch_help.contains("Download"));

        let inspect_help = execute_help(Some("inspect")).expect("operation should succeed");
        assert!(inspect_help.contains("Inspect"));

        let memory_help = execute_help(Some("memory")).expect("operation should succeed");
        assert!(memory_help.contains("memory"));

        let distill_help = execute_help(Some("distill")).expect("operation should succeed");
        assert!(distill_help.contains("distill"));

        let general_help = execute_help(None).expect("operation should succeed");
        assert!(general_help.contains("Available commands"));
    }

    /// ONT-10 S14: general help must list every canonical command the parser accepts,
    /// or a help-walk extractor reads the missing one as a ledger orphan (`clear` was).
    #[test]
    fn test_general_help_lists_every_parsed_command() {
        let general_help = execute_help(None).expect("operation should succeed");
        let listed: Vec<&str> = general_help
            .lines()
            .skip(1)
            .filter_map(|l| l.split_whitespace().next())
            .collect();
        for name in [
            "fetch", "inspect", "memory", "set", "distill", "export", "history", "help", "clear",
            "quit",
        ] {
            assert!(
                !matches!(parse(name), Ok(Command::Unknown { .. })),
                "{name} must be a parsed command"
            );
            assert!(listed.contains(&name), "general help omits `{name}`");
        }
        assert_eq!(listed.len(), 10, "help lists {listed:?}");
    }

    #[test]
    fn test_detect_architecture_variants() {
        assert_eq!(detect_architecture("meta-llama/Llama-2-7b"), "llama");
        assert_eq!(detect_architecture("bert-base-uncased"), "bert");
        assert_eq!(detect_architecture("openai-gpt"), "gpt");
        assert_eq!(detect_architecture("mistralai/Mistral-7B"), "mistral");
        assert_eq!(detect_architecture("Qwen/Qwen2.5-Coder-0.5B"), "qwen");
        assert_eq!(detect_architecture("microsoft/phi-2"), "phi");
        assert_eq!(detect_architecture("tiiuae/falcon-7b"), "falcon");
        assert_eq!(detect_architecture("mistralai/Mixtral-8x7B"), "mistral");
        assert_eq!(detect_architecture("custom-model"), "unknown");
    }

    // =========================================================================
    // FALSIFY tests — contract violation sweep (N-04)
    // =========================================================================

    #[test]
    fn test_falsify_n04_mistral_before_llama_in_ambiguous_id() {
        // N-04: "mistral" must be checked before "llama" since some Mistral
        // model IDs contain both substrings. Mistral-specific detection
        // should take priority.
        assert_eq!(
            detect_architecture("mistral-llama-variant"),
            "mistral",
            "Mistral should take priority over LLaMA in ambiguous IDs"
        );
    }

    #[test]
    fn test_falsify_n04_unknown_is_explicit() {
        // N-04: Unknown architecture must be an explicit "unknown" string,
        // never an empty string or a silent default to a known architecture.
        let result = detect_architecture("totally-custom-model-v3");
        assert_eq!(result, "unknown");
        assert!(!result.is_empty());
    }

    #[test]
    fn test_estimate_params_variants() {
        assert_eq!(estimate_params("model-70b"), 70_000_000_000);
        assert_eq!(estimate_params("model-13b"), 13_000_000_000);
        assert_eq!(estimate_params("model-7b"), 7_000_000_000);
        assert_eq!(estimate_params("model-1.1b"), 1_100_000_000);
        assert_eq!(estimate_params("bert-base"), 350_000_000);
    }

    #[test]
    fn test_estimate_layers_variants() {
        assert_eq!(estimate_layers("model-70b"), 80);
        assert_eq!(estimate_layers("model-13b"), 40);
        assert_eq!(estimate_layers("model-7b"), 32);
        assert_eq!(estimate_layers("bert-base"), 12);
    }

    #[test]
    fn test_execute_set_invalid_number() {
        let mut state = SessionState::new();
        let result = execute_set("batch_size", "not_a_number", &mut state);
        assert!(result.is_err());
    }

    #[test]
    fn test_execute_set_unknown_key() {
        let mut state = SessionState::new();
        let result = execute_set("unknown_setting", "value", &mut state);
        assert!(result.is_err());
    }

    #[test]
    fn test_execute_distill_no_teacher() {
        let state = SessionState::new();
        let result = execute_distill(true, &state);
        assert!(result.is_err());
    }

    #[test]
    fn test_execute_distill_no_student() {
        let mut state = SessionState::new();
        let model = LoadedModel {
            id: "teacher".to_string(),
            path: std::path::PathBuf::from("/tmp"),
            architecture: "llama".to_string(),
            parameters: 7_000_000_000,
            layers: 32,
            hidden_dim: 4096,
            role: ModelRole::Teacher,
        };
        state.add_model("teacher".to_string(), model);

        let result = execute_distill(true, &state);
        assert!(result.is_err());
    }

    #[test]
    fn test_execute_distill_success() {
        let mut state = SessionState::new();

        let teacher = LoadedModel {
            id: "teacher/model".to_string(),
            path: std::path::PathBuf::from("/tmp/t"),
            architecture: "llama".to_string(),
            parameters: 7_000_000_000,
            layers: 32,
            hidden_dim: 4096,
            role: ModelRole::Teacher,
        };
        state.add_model("teacher".to_string(), teacher);

        let student = LoadedModel {
            id: "student/model".to_string(),
            path: std::path::PathBuf::from("/tmp/s"),
            architecture: "llama".to_string(),
            parameters: 1_000_000_000,
            layers: 12,
            hidden_dim: 2048,
            role: ModelRole::Student,
        };
        state.add_model("student".to_string(), student);

        let result = execute_distill(true, &state).expect("operation should succeed");
        assert!(result.contains("Dry run"));
    }

    #[test]
    fn test_execute_export_refuses_rather_than_fabricating() {
        let state = SessionState::new();
        let result = execute_export("safetensors", "/tmp/model.st", &state);
        // It must FAIL. Previously it returned Ok("Exported to ...") having
        // written nothing, and this test asserted that string -- so the test
        // locked the defect in, the same shape as the `wgpu_available = true`
        // hole found in finetune_tests.rs.
        assert!(
            result.is_err(),
            "export must not report success without exporting"
        );
        let msg = format!("{}", result.unwrap_err());
        assert!(
            !msg.contains("Exported to"),
            "the error must not read like a success: {msg}"
        );
        assert!(msg.contains("not implemented"), "must say why: {msg}");
    }

    #[test]
    fn test_execute_export_leaves_no_file_behind() {
        // Non-vacuity control: prove the refusal is not merely a message change
        // by confirming nothing is written where it claimed to write.
        let state = SessionState::new();
        let path = std::env::temp_dir().join("apr-2519-export-probe.st");
        let _ = std::fs::remove_file(&path);
        let _ = execute_export(
            "safetensors",
            path.to_str().expect("utf-8 temp path"),
            &state,
        );
        assert!(!path.exists(), "export refused but still created {path:?}");
    }

    #[test]
    fn test_parse_empty_input() {
        let cmd = parse("").expect("parsing should succeed");
        assert!(matches!(cmd, Command::Unknown { .. }));
    }

    #[test]
    fn test_execute_memory_with_args() {
        let state = SessionState::new();
        let result =
            execute_memory(Some(64), Some(1024), &state).expect("operation should succeed");
        assert!(result.contains("batch=64"));
        assert!(result.contains("seq=1024"));
    }

    #[test]
    fn test_command_enum_equality() {
        assert_eq!(Command::Quit, Command::Quit);
        assert_eq!(Command::Clear, Command::Clear);
        assert_eq!(Command::History, Command::History);
    }
}