hf2q 0.1.3

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! hf2q — Pure Rust CLI for quantizing HuggingFace models to GGUF and safetensors.
//!
//! Entry point: dispatches clap subcommands to appropriate handlers.
//!
//! Exit codes:
//!   0 = success
//!   1 = conversion error
//!   2 = quality threshold exceeded
//!   3 = input/validation error

pub mod arch;
pub mod backends;
pub mod cli;
// `core` is the in-place precursor to the planned `hf2q-core` crate
// (workspace v0.1.0 split). See `src/core/mod.rs` for the boundary
// rule and the planned submodule layout.
pub mod convert;
pub mod core;
mod debug;
mod doctor;
pub mod gguf_patch;
pub mod inference;
pub mod input;
pub mod intelligence;
pub mod ir;
pub mod models;
pub mod progress;
pub mod quantize;
mod serve;

use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::Parser;
use tracing::error;

use cli::{Cli, Command};

/// Exit codes.
///
/// 0/1/3 are the long-standing convert codes.  4–6 are added by
/// ADR-012 P8's `hf2q smoke` subcommand for distinct preflight failure modes
/// (per Decision 16 acceptance: each preflight failure surfaces a unique
/// non-zero code so a CI runner can tell "missing token" from "missing disk").
const EXIT_SUCCESS: u8 = 0;
const EXIT_CONVERSION_ERROR: u8 = 1;
const EXIT_INPUT_ERROR: u8 = 3;

/// Error types for exit code classification.
#[derive(Debug)]
enum AppError {
    Input(anyhow::Error),
    Conversion(anyhow::Error),
    /// Smoke-subcommand exit codes per ADR-012 Decision 16 §preflight (2-8).
    /// Carries the smoke-specific code so the process exits with the
    /// documented value rather than the generic `EXIT_CONVERSION_ERROR=1`
    /// AppError default. Without this variant, every distinct smoke
    /// failure mode collapses to exit 1 — defeating Decision 16's
    /// "distinct non-zero code" contract at the OS-process level.
    Smoke {
        code: u8,
        msg: anyhow::Error,
    },
}

impl AppError {
    fn exit_code(&self) -> u8 {
        match self {
            AppError::Input(_) => EXIT_INPUT_ERROR,
            AppError::Conversion(_) => EXIT_CONVERSION_ERROR,
            AppError::Smoke { code, .. } => *code,
        }
    }
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AppError::Input(e) => write!(f, "{:#}", e),
            AppError::Conversion(e) => write!(f, "{:#}", e),
            AppError::Smoke { msg, .. } => write!(f, "{:#}", msg),
        }
    }
}

fn main() -> ExitCode {
    // Emit one-shot warning / ack-gate summary for any investigation-only
    // env vars that are set. Uses direct eprintln! (not tracing), so it
    // runs correctly before the subscriber is installed. Placed before
    // Cli::parse so the warning appears even when clap exits early on
    // --help or --version.
    debug::INVESTIGATION_ENV.activate();

    let cli = Cli::parse();

    // Logging subscriber init. Priority:
    //   1. --log-level (explicit) overrides everything.
    //   2. -v/-vv/-vvv bumps verbosity.
    //   3. RUST_LOG env var.
    //   4. Default: hf2q=warn (silent on the generate boot path).
    // Log format (text/json) comes from --log-format (Decision #11).
    // Stderr writer: logs never touch stdout, keeping the generation
    // stream unpolluted. ANSI colors only when stderr is a TTY for
    // text format; JSON format is always ANSI-free.
    use std::io::IsTerminal;
    use tracing_subscriber::EnvFilter;
    let filter = if let Some(lvl) = cli.log_level {
        EnvFilter::new(format!("hf2q={lvl},mlx_native={lvl}", lvl = lvl.as_str()))
    } else {
        match cli.verbose {
            0 => EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("hf2q=warn")),
            1 => EnvFilter::new("hf2q=info,mlx_native=info"),
            2 => EnvFilter::new("hf2q=debug,mlx_native=debug"),
            _ => EnvFilter::new("hf2q=trace,mlx_native=trace"),
        }
    };
    let stderr_is_tty = std::io::stderr().is_terminal();
    match cli.log_format {
        cli::LogFormat::Text => {
            tracing_subscriber::fmt()
                .with_env_filter(filter)
                .with_writer(std::io::stderr)
                .with_ansi(stderr_is_tty)
                .without_time()
                .init();
        }
        cli::LogFormat::Json => {
            tracing_subscriber::fmt()
                .json()
                .with_env_filter(filter)
                .with_writer(std::io::stderr)
                .with_current_span(false)
                .with_span_list(false)
                .init();
        }
    }

    match run(cli) {
        Ok(()) => ExitCode::from(EXIT_SUCCESS),
        Err(app_err) => {
            let exit_code = app_err.exit_code();
            error!("{}", app_err);
            eprintln!("Error: {}", app_err);
            ExitCode::from(exit_code)
        }
    }
}

fn run(cli: Cli) -> Result<(), AppError> {
    match cli.command {
        Command::GgufPatch(args) => cmd_gguf_patch(args),
        Command::Info(args) => cmd_info(args).map_err(AppError::Input),
        Command::Doctor => doctor::run_doctor().map_err(AppError::Conversion),
        Command::Completions(args) => cmd_completions(args).map_err(AppError::Input),
        Command::Generate(args) => serve::cmd_generate(args).map_err(AppError::Conversion),
        Command::Serve(args) => serve::cmd_serve(args).map_err(AppError::Conversion),
        Command::Parity(args) => serve::cmd_parity(args).map_err(AppError::Conversion),
        Command::Smoke(args) => cmd_smoke(args),
        // ADR-005 Phase 3 iter-205 (AC line 5351): operator-facing
        // cache management.  Errors map to AppError::Input because
        // every failure surface (unknown_repo, unknown_quant, missing
        // --yes, mutually-exclusive-flags) is a user-input mistake;
        // exit-3 is the documented signal.
        Command::Cache(args) => serve::cmd_cache(args).map_err(AppError::Input),
        Command::Convert(args) => cmd_convert(args),
        Command::Tokenizer(args) => cmd_tokenizer(args),
    }
}

/// ADR-038 G4-CFA-5e — operator-facing tokenizer.json patching.
fn cmd_tokenizer(args: cli::TokenizerArgs) -> Result<(), AppError> {
    use cli::TokenizerAction;
    match args.action {
        TokenizerAction::FixBos {
            path,
            gguf,
            bos_id,
            bos_text,
        } => {
            // If a sibling GGUF is provided, read BOS metadata from it
            // (matches the runtime adapter's resolution path).
            let (resolved_id, resolved_text) = if let Some(gguf_path) = gguf {
                let g = mlx_native::gguf::GgufFile::open(&gguf_path).map_err(|e| {
                    AppError::Input(anyhow::anyhow!("open GGUF {}: {e}", gguf_path.display()))
                })?;
                let id = g
                    .metadata_u32("tokenizer.ggml.bos_token_id")
                    .ok_or_else(|| {
                        AppError::Input(anyhow::anyhow!(
                            "GGUF {} has no tokenizer.ggml.bos_token_id metadata",
                            gguf_path.display()
                        ))
                    })?;
                // The runtime adapter resolves BOS *text* via the
                // tokenizer's vocab. Here we don't have the tokenizer
                // loaded yet (we're about to patch its file), so fall
                // back to the operator-supplied `--bos-text` default.
                (id, bos_text)
            } else {
                (bos_id, bos_text)
            };

            let mutated =
                core::tokenizer_adapter::fix_tokenizer_json_bos(&path, &resolved_text, resolved_id)
                    .map_err(|e| {
                        AppError::Input(anyhow::anyhow!(
                            "fix_tokenizer_json_bos {}: {e}",
                            path.display()
                        ))
                    })?;
            if mutated {
                println!(
                    "Patched {}: prepended BOS SpecialToken {:?} (id={}) to post_processor.single",
                    path.display(),
                    resolved_text,
                    resolved_id,
                );
            } else {
                println!(
                    "No change to {}: post_processor.single already starts with BOS SpecialToken {:?}",
                    path.display(), resolved_text,
                );
            }
            Ok(())
        }
    }
}

/// ADR-033 P4 — drive the convert pipeline.
///
/// Parses `--quant <name>` via `QuantSelector::from_name`, resolves the
/// HF input directory (positional `<hf_dir>` OR auto-download via
/// `--repo <hf_repo>`; mutually exclusive — B1), hands the result to
/// [`crate::convert::run_convert`], and maps the typed `ConvertError`
/// onto `AppError::Input` (parse / arch / missing tensor — operator-input
/// issues) vs `AppError::Conversion` (source read, orchestrator, IO —
/// pipeline-internal issues).
fn cmd_convert(args: cli::ConvertCliArgs) -> Result<(), AppError> {
    use crate::convert::{
        run_convert, ConvertArgs, ConvertError, QuantSelector, RemoteConversionSource,
    };

    // QuantSelector parses both standard ftypes (`q5_k_m`, `q8_0`, ...)
    // and Apex tiers (`apex-balanced`, `apex-i-quality`, ...). Reserved
    // names (`dwq`, bare `apex`, `tq1_0`, `tq2_0`) surface as typed
    // errors per ADR §6 reserved-name stubs.
    let selector = QuantSelector::from_name(&args.quant)
        .map_err(|e| AppError::Input(anyhow::anyhow!("{e}")))?;
    let source_repo = args.source_repo.clone();
    let source_revision = args.source_revision.clone();

    // ----- B1: resolve HF input directory ---------------------------------
    // Exactly one of {positional <hf_dir>, --repo <hf_repo>} must be set.
    // clap's `conflicts_with` rejects the "both set" case at parse time;
    // we still guard here as defense-in-depth so the typed error variant
    // survives any future plumbing change that bypasses clap.
    let (hf_dir, mut remote_source) = match (args.hf_dir, args.repo, args.revision) {
        (Some(_), Some(_), _) => {
            return Err(AppError::Input(anyhow::anyhow!(
                "{}",
                ConvertError::RepoAndDirMutuallyExclusive
            )));
        }
        (Some(_), None, Some(_)) => {
            return Err(AppError::Input(anyhow::anyhow!(
                "{}",
                ConvertError::RevisionRequiresRepo
            )));
        }
        (Some(path), None, None) => (path, None),
        (None, Some(repo), revision) => {
            validate_hf_repo_id(&repo).map_err(|e| AppError::Input(anyhow::anyhow!("{e}")))?;
            let revision = immutable_hf_revision(revision.as_deref())
                .map_err(|e| AppError::Input(anyhow::anyhow!("{e}")))?;
            let path = download_repo_via_hf_cli(&repo, &revision)
                .map_err(|e| AppError::Conversion(anyhow::anyhow!("{e}")))?;
            let verified =
                crate::input::integrity::verify_remote_conversion_source(&repo, &revision, &path)
                    .map_err(|e| AppError::Conversion(anyhow::anyhow!("{e}")))?;
            let source = RemoteConversionSource::from_verified(repo, revision, &path, &verified)
                .map_err(|e| AppError::Conversion(anyhow::anyhow!("{e}")))?;
            (path, Some(source))
        }
        (None, None, _) => {
            return Err(AppError::Input(anyhow::anyhow!(
                "convert: either positional `<hf_dir>` or `--repo <hf_repo>` is required"
            )));
        }
    };

    if let Some(repo) = source_repo {
        validate_hf_repo_id(&repo).map_err(|e| AppError::Input(anyhow::anyhow!("{e}")))?;
        let revision = immutable_hf_revision(source_revision.as_deref())
            .map_err(|e| AppError::Input(anyhow::anyhow!("{e}")))?;
        let verified =
            crate::input::integrity::verify_remote_conversion_source(&repo, &revision, &hf_dir)
                .map_err(|e| AppError::Conversion(anyhow::anyhow!("{e}")))?;
        remote_source = Some(
            RemoteConversionSource::from_verified(repo, revision, &hf_dir, &verified)
                .map_err(|e| AppError::Conversion(anyhow::anyhow!("{e}")))?,
        );
    }

    let resolved = ConvertArgs {
        hf_dir,
        selector,
        output: args.output,
        dry_run: args.dry_run,
        imatrix: args.imatrix,
        imatrix_corpus: args.imatrix_corpus,
        imatrix_out: args.imatrix_out,
        imatrix_n_ctx: args.imatrix_n_ctx,
        mmproj: args.mmproj,
        remote_source,
    };
    run_convert(resolved).map_err(|e| match e {
        ConvertError::UnsupportedArch { .. }
        | ConvertError::UnmappedTensor { .. }
        | ConvertError::MissingHparam { .. }
        | ConvertError::IncompleteExpertGroup { .. }
        | ConvertError::DuplicateExpertIndex { .. }
        | ConvertError::ApexMissingLayerCount
        | ConvertError::ApexCustomOutOfScope { .. }
        | ConvertError::Apex(_)
        | ConvertError::Tokenizer(_)
        | ConvertError::Imatrix(_)
        | ConvertError::ImatrixRequiredForITier { .. }
        | ConvertError::ImatrixNCtxInvalid { .. }
        | ConvertError::RepoAndDirMutuallyExclusive
        | ConvertError::ImmutableRevisionRequired { .. }
        | ConvertError::RevisionRequiresRepo
        | ConvertError::InvalidRepoId { .. } => AppError::Input(anyhow::anyhow!("{e}")),
        ConvertError::Source(_)
        | ConvertError::Orchestrator(_)
        | ConvertError::Io(_)
        | ConvertError::Integrity(_)
        | ConvertError::Receipt(_)
        | ConvertError::HfDownload { .. } => AppError::Conversion(anyhow::anyhow!("{e}")),
    })
}

/// B1 — sanitize an HF repo id for filesystem use.
///
/// Replaces every `/` with `__` so `google/gemma-4-26b-a4b-it` becomes
/// `google__gemma-4-26b-a4b-it`. Other characters pass through.
/// Centralized as a pure function so the unit test can pin the contract
/// without invoking the download subprocess.
fn sanitize_repo_for_cache_dir(repo: &str) -> String {
    let mut sanitized = String::with_capacity(repo.len() + 4);
    for c in repo.chars() {
        match c {
            '/' => sanitized.push_str("__"),
            c if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') => sanitized.push(c),
            _ => sanitized.push('_'),
        }
    }
    if matches!(sanitized.as_str(), "" | "." | "..") {
        sanitized.insert(0, '_');
    }
    sanitized
}

fn immutable_hf_revision(revision: Option<&str>) -> Result<String, crate::convert::ConvertError> {
    let Some(revision) = revision else {
        return Err(crate::convert::ConvertError::ImmutableRevisionRequired { supplied: None });
    };
    if revision.len() != 40 || !revision.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(crate::convert::ConvertError::ImmutableRevisionRequired {
            supplied: Some(revision.to_string()),
        });
    }
    Ok(revision.to_ascii_lowercase())
}

fn validate_hf_repo_id(repo: &str) -> Result<(), crate::convert::ConvertError> {
    let valid = !repo.is_empty()
        && !repo.starts_with('-')
        && repo.split('/').all(|component| {
            !component.is_empty()
                && !matches!(component, "." | "..")
                && component
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        });
    if valid {
        Ok(())
    } else {
        Err(crate::convert::ConvertError::InvalidRepoId {
            repo: repo.to_string(),
        })
    }
}

/// Download source artifacts with the explicitly allowed `hf` CLI and
/// return the revision-scoped cache directory on success.
///
/// `<cache>` = `~/.cache/hf2q/repos/<sanitize_repo_for_cache_dir(repo)>/<revision>/`.
/// The directory is created if missing; existing partial downloads are
/// resumed by `hf`'s own logic. On non-zero exit, captured stderr is
/// returned through the typed
/// `ConvertError::HfDownload` variant.
fn download_repo_via_hf_cli(
    repo: &str,
    revision: &str,
) -> Result<PathBuf, crate::convert::ConvertError> {
    use crate::convert::ConvertError;

    // Resolve cache root: ~/.cache/hf2q/repos/<sanitized>/.
    // `home::home_dir()` is unavailable in std; fall back to $HOME env.
    let home = std::env::var("HOME").map_err(|_| ConvertError::HfDownload {
        repo: repo.to_string(),
        exit_code: None,
        stderr: "HOME env var not set — cannot resolve ~/.cache/hf2q/repos/".to_string(),
    })?;
    let cache_dir = PathBuf::from(home)
        .join(".cache")
        .join("hf2q")
        .join("repos")
        .join(sanitize_repo_for_cache_dir(repo))
        .join(revision);
    std::fs::create_dir_all(&cache_dir).map_err(|e| ConvertError::HfDownload {
        repo: repo.to_string(),
        exit_code: None,
        stderr: format!("failed to create cache dir `{}`: {e}", cache_dir.display()),
    })?;

    eprintln!(
        "[hf2q convert --repo] downloading {repo}@{revision}{} via hf",
        cache_dir.display()
    );

    let output = hf_download_command(repo, revision, &cache_dir).output();

    let output = match output {
        Ok(o) => o,
        Err(e) => {
            return Err(ConvertError::HfDownload {
                repo: repo.to_string(),
                exit_code: None,
                stderr: format!(
                    "failed to spawn `hf`: {e} \
                     (is the HuggingFace CLI on PATH? `pip install -U huggingface_hub[cli]`)"
                ),
            });
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
        return Err(ConvertError::HfDownload {
            repo: repo.to_string(),
            exit_code: output.status.code(),
            stderr,
        });
    }

    Ok(cache_dir)
}

fn hf_download_command(
    repo: &str,
    revision: &str,
    cache_dir: &std::path::Path,
) -> std::process::Command {
    let mut command = std::process::Command::new("hf");
    command
        .arg("download")
        .arg(repo)
        .arg("--revision")
        .arg(revision)
        .arg("--local-dir")
        .arg(cache_dir);
    for pattern in ["*.safetensors", "*.json", "tokenizer.model", "README.md"] {
        command.arg("--include").arg(pattern);
    }
    for pattern in [
        "*.gguf",
        "*.bin",
        "*.pt",
        "*.pth",
        "*.onnx",
        "*.h5",
        "*.msgpack",
    ] {
        command.arg("--exclude").arg(pattern);
    }
    command
}

fn cmd_gguf_patch(args: cli::GgufPatchArgs) -> Result<(), AppError> {
    if !args.dry_run && !args.in_place && args.output.is_none() {
        return Err(AppError::Input(anyhow::anyhow!(
            "gguf-patch requires --output <out> or --in-place unless --dry-run is set"
        )));
    }

    gguf_patch::patch_chat_template_from_arch(gguf_patch::GgufPatchOptions {
        input: args.input,
        output: args.output,
        in_place: args.in_place,
        dry_run: args.dry_run,
    })
    .map(|_| ())
    .map_err(AppError::Conversion)
}

/// Handle the `smoke` subcommand — ADR-012 Decision 16.
///
/// Dispatches via `ArchRegistry::get(arch)` — unknown arches (including
/// gemma4, ministral, deepseekv3, bogus) return a uniform structured
/// error. Preflight failures map to the documented exit codes 2-6.
fn cmd_smoke(args: cli::SmokeArgs) -> Result<(), AppError> {
    let smoke_args = arch::smoke::SmokeArgs {
        arch: args.arch,
        quant: arch::smoke::normalize_quant_label(&args.quant),
        with_vision: args.with_vision,
        skip_convert: args.skip_convert,
        dry_run: args.dry_run,
        fixtures_root: args.fixtures_root,
        local_dir: args.local_dir,
        convert_output_dir: args.convert_output_dir,
        llama_cli_override: args.llama_cli_override,
    };
    let env = arch::smoke::RealSmokeEnv {
        convert_dir: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    };
    let outcome = arch::smoke::dispatch(&smoke_args, &env);
    let code = outcome.exit_code();
    let rendered = arch::smoke::render_outcome(&outcome);
    if matches!(
        outcome,
        arch::smoke::SmokeOutcome::Pass { .. } | arch::smoke::SmokeOutcome::Skipped { .. }
    ) {
        println!("{}", rendered);
        Ok(())
    } else {
        // Preflight / unknown-arch — propagate the smoke-specific exit
        // code (Decision 16 §preflight: 2-8 distinct non-zero codes)
        // rather than collapsing to AppError::Conversion's exit 1.
        // Without `AppError::Smoke`, the documented exit codes were
        // shadowed at the process boundary — fixed in this commit.
        eprintln!("{}", rendered);
        Err(AppError::Smoke {
            code,
            msg: anyhow::anyhow!("{}", rendered),
        })
    }
}

/// Handle the `info` subcommand.
fn cmd_info(args: cli::InfoArgs) -> Result<()> {
    let input_dir = resolve_info_input(&args)?;

    let config_path = input_dir.join("config.json");
    if !config_path.exists() {
        anyhow::bail!(
            "No config.json found in {}. Is this a HuggingFace model directory?",
            input_dir.display()
        );
    }

    let metadata =
        input::config_parser::parse_config(&config_path).context("Failed to parse model config")?;

    println!();
    println!("{}", console::style("Model Information").bold().green());
    println!("{}", input::config_parser::format_info(&metadata));
    println!();

    Ok(())
}

/// Resolve the input directory for the info subcommand.
fn resolve_info_input(args: &cli::InfoArgs) -> Result<PathBuf> {
    match (&args.input, &args.repo) {
        (Some(path), None) => {
            if !path.exists() {
                anyhow::bail!("Input directory does not exist: {}", path.display());
            }
            Ok(path.clone())
        }
        (None, Some(repo_id)) => {
            let progress = progress::ProgressReporter::new();
            let download_dir = input::hf_download::download_model(repo_id, &progress)
                .context("Failed to download model from HuggingFace Hub")?;
            Ok(download_dir)
        }
        (None, None) => {
            anyhow::bail!("Either --input or --repo must be specified");
        }
        (Some(_), Some(_)) => {
            anyhow::bail!("--input and --repo are mutually exclusive");
        }
    }
}

/// Handle the `completions` subcommand.
fn cmd_completions(args: cli::CompletionsArgs) -> Result<()> {
    use clap::CommandFactory;
    use clap_complete::generate;

    let mut cmd = Cli::command();
    generate(args.shell, &mut cmd, "hf2q", &mut std::io::stdout());

    Ok(())
}

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

    /// B1 — `/` in the HF repo id is replaced with `__` so the
    /// resulting string is filesystem-safe. Pins the exact spec from
    /// the rename/B1 mission.
    #[test]
    fn sanitize_repo_for_cache_dir_replaces_slash_with_double_underscore() {
        assert_eq!(
            sanitize_repo_for_cache_dir("google/gemma-4-26b-a4b-it"),
            "google__gemma-4-26b-a4b-it"
        );
    }

    /// B1 — repo without `/` passes through unchanged (degenerate input
    /// from a custom local URL alias; we still want it filesystem-safe).
    #[test]
    fn sanitize_repo_for_cache_dir_passes_through_when_no_slash() {
        assert_eq!(sanitize_repo_for_cache_dir("local-only"), "local-only");
    }

    /// B1 — repo with multiple `/` (uncommon HF nested-org pattern)
    /// replaces every separator, not just the first.
    #[test]
    fn sanitize_repo_for_cache_dir_replaces_every_slash() {
        assert_eq!(
            sanitize_repo_for_cache_dir("org/sub/model"),
            "org__sub__model"
        );
    }

    /// B1 — `cmd_convert` rejects "both `<hf_dir>` and `--repo`" with
    /// the typed `RepoAndDirMutuallyExclusive` variant, mapped to
    /// `AppError::Input` (exit code 3). clap's `conflicts_with` should
    /// catch this at parse time; this test pins the defense-in-depth
    /// path in case clap's rules change.
    #[test]
    fn cmd_convert_rejects_repo_and_dir_both_set() {
        let args = cli::ConvertCliArgs {
            hf_dir: Some(PathBuf::from("/tmp/example")),
            repo: Some("org/repo".to_string()),
            revision: Some("a".repeat(40)),
            source_repo: None,
            source_revision: None,
            quant: "q8_0".to_string(),
            output: PathBuf::from("/tmp/out.gguf"),
            dry_run: false,
            imatrix: None,
            imatrix_corpus: None,
            imatrix_out: None,
            imatrix_n_ctx: None,
            mmproj: false,
        };
        let err = cmd_convert(args).expect_err("must error");
        match err {
            AppError::Input(e) => {
                let s = format!("{e:#}");
                assert!(
                    s.contains("mutually exclusive"),
                    "expected mutually-exclusive diagnostic, got `{s}`"
                );
            }
            other => panic!("expected AppError::Input, got {other:?}"),
        }
    }

    #[test]
    fn immutable_revision_accepts_and_normalizes_exact_sha() {
        let upper = "A".repeat(40);
        assert_eq!(immutable_hf_revision(Some(&upper)).unwrap(), "a".repeat(40));
    }

    #[test]
    fn immutable_revision_rejects_missing_branch_and_short_sha() {
        assert!(matches!(
            immutable_hf_revision(None),
            Err(crate::convert::ConvertError::ImmutableRevisionRequired { supplied: None })
        ));
        for mutable in ["main", "v1.0", "deadbeef"] {
            assert!(matches!(
                immutable_hf_revision(Some(mutable)),
                Err(crate::convert::ConvertError::ImmutableRevisionRequired { supplied: Some(_) })
            ));
        }
    }

    #[test]
    fn cmd_convert_rejects_mutable_remote_revision_before_download() {
        let args = cli::ConvertCliArgs {
            hf_dir: None,
            repo: Some("org/model".into()),
            revision: Some("main".into()),
            source_repo: None,
            source_revision: None,
            quant: "q8_0".into(),
            output: PathBuf::from("unused.gguf"),
            dry_run: false,
            imatrix: None,
            imatrix_corpus: None,
            imatrix_out: None,
            imatrix_n_ctx: None,
            mmproj: false,
        };
        let err = cmd_convert(args).expect_err("mutable revision must fail before download");
        assert!(matches!(err, AppError::Input(_)));
        assert!(err.to_string().contains("40-hex-commit"));
    }

    #[test]
    fn cmd_convert_rejects_mutable_local_source_revision_before_hashing() {
        let args = cli::ConvertCliArgs {
            hf_dir: Some(PathBuf::from("/tmp/example")),
            repo: None,
            revision: None,
            source_repo: Some("org/model".into()),
            source_revision: Some("main".into()),
            quant: "deepseek4-agentic-q2".into(),
            output: PathBuf::from("unused.gguf"),
            dry_run: false,
            imatrix: None,
            imatrix_corpus: None,
            imatrix_out: None,
            imatrix_n_ctx: None,
            mmproj: false,
        };
        let err = cmd_convert(args).expect_err("mutable revision must fail before hashing");
        assert!(matches!(err, AppError::Input(_)));
        assert!(err.to_string().contains("40-hex-commit"));
    }

    #[test]
    fn cache_slug_cannot_resolve_to_parent_component() {
        assert_eq!(sanitize_repo_for_cache_dir(".."), "_..");
        assert_eq!(
            sanitize_repo_for_cache_dir("org/../../model"),
            "org__..__..__model"
        );
    }

    #[test]
    fn repo_validation_blocks_option_and_path_injection() {
        for invalid in ["", "--help", "../model", "org//model", "org/model?"] {
            assert!(
                validate_hf_repo_id(invalid).is_err(),
                "accepted {invalid:?}"
            );
        }
        validate_hf_repo_id("deepseek-ai/DeepSeek-V4").unwrap();
    }

    #[test]
    fn hf_download_command_repeats_source_include_and_quant_exclude_flags() {
        let command = hf_download_command(
            "org/model",
            &"a".repeat(40),
            std::path::Path::new("/tmp/hf2q-fixture"),
        );
        assert_eq!(command.get_program(), "hf");
        let args: Vec<_> = command
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(args.iter().filter(|arg| *arg == "--include").count(), 4);
        assert_eq!(args.iter().filter(|arg| *arg == "--exclude").count(), 7);
        assert!(args
            .windows(2)
            .any(|pair| pair[0] == "--revision" && pair[1] == "a".repeat(40)));
        assert!(args
            .windows(2)
            .any(|pair| pair[0] == "--exclude" && pair[1] == "*.gguf"));
    }
}