apr-cli 0.30.0

CLI tool for APR model inspection, debugging, and operations
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
//! Export command implementation (GH-246)
//!
//! Exports APR models to other formats for different ecosystems:
//! - SafeTensors (.safetensors) - HuggingFace ecosystem
//! - GGUF (.gguf) - llama.cpp / local inference
//! - MLX (directory) - Apple Silicon inference
//! - ONNX (.onnx) - Cross-framework inference (planned)
//! - OpenVINO (.xml/.bin) - Intel inference (planned)
//! - CoreML (.mlpackage) - iOS/macOS deployment (planned)
//!
//! # Example
//!
//! ```bash
//! apr export model.apr --format gguf -o model.gguf
//! apr export model.apr --format mlx -o model-mlx/
//! apr export model.apr --batch gguf,mlx -o exports/
//! apr export --list-formats --json
//! ```

use crate::error::{CliError, Result};
use crate::output;
use aprender::format::{apr_export, ExportFormat, ExportOptions, ExportReport, QuantizationType};
use humansize::{format_size, BINARY};
use std::path::Path;

/// GH-273: Resolve export format (infer from output extension) and parse quantization.
fn resolve_export_options(
    format: &str,
    output: &Path,
    quantize: Option<&str>,
) -> Result<(ExportFormat, Option<QuantizationType>)> {
    // GH-273: Infer export format from output extension when --format is default
    let effective_format = if format == "safetensors" {
        let ext = output.extension().and_then(|e| e.to_str()).unwrap_or("");
        match ext {
            "gguf" => "gguf",
            "mlx" => "mlx",
            "onnx" => "onnx",
            _ => format,
        }
    } else {
        format
    };

    let export_format: ExportFormat = effective_format.parse().map_err(|_| {
        CliError::ValidationFailed(format!(
            "Unknown export format: {effective_format}. Use: safetensors, gguf, mlx, onnx, openvino, coreml"
        ))
    })?;

    if !export_format.is_supported() {
        return Err(CliError::ValidationFailed(format!(
            "Export format '{}' is not yet implemented. Supported: safetensors, gguf, mlx",
            export_format.display_name()
        )));
    }

    let quant_type = parse_quantization(quantize)?;
    Ok((export_format, quant_type))
}

/// Execute the export and display results.
fn execute_and_display(
    file: &Path,
    output: &Path,
    export_format: ExportFormat,
    quant_type: Option<QuantizationType>,
    json_output: bool,
) -> Result<()> {
    let options = ExportOptions {
        format: export_format,
        quantize: quant_type,
        ..Default::default()
    };

    match apr_export(file, output, options) {
        Ok(report) => {
            if json_output {
                display_report_json(&report);
            } else {
                display_report(&report);
            }
            Ok(())
        }
        Err(e) => {
            if !json_output {
                println!();
                println!("  {}", output::badge_fail("Export failed"));
            }
            Err(CliError::ValidationFailed(e.to_string()))
        }
    }
}

/// Run the export plan for batch mode (multiple formats).
#[allow(clippy::disallowed_methods)]
fn run_plan_batch(
    file: &Path,
    file_size: u64,
    batch_formats: &str,
    quantize: Option<&str>,
    output: Option<&Path>,
    json_output: bool,
) -> Result<()> {
    let formats: Vec<ExportFormat> = batch_formats
        .split(',')
        .map(|s| {
            s.trim()
                .parse::<ExportFormat>()
                .map_err(|_| CliError::ValidationFailed(format!("Unknown format in batch: {s}")))
        })
        .collect::<Result<Vec<_>>>()?;

    for f in &formats {
        if !f.is_supported() {
            return Err(CliError::ValidationFailed(format!(
                "Format '{}' in batch is not yet supported",
                f.display_name()
            )));
        }
    }

    let quant_type = parse_quantization(quantize)?;

    if json_output {
        let json = serde_json::json!({
            "plan": true,
            "status": "valid",
            "input": file.display().to_string(),
            "input_size": file_size,
            "batch": true,
            "formats": formats.iter().map(|f| f.display_name()).collect::<Vec<_>>(),
            "quantization": quant_type.as_ref().map(|q| format!("{q:?}")),
            "output_dir": output.map(|p| p.display().to_string()),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        output::header("APR Export — Plan (Batch)");
        let pairs: Vec<(&str, String)> = vec![
            (
                "Input",
                format!(
                    "{} ({})",
                    file.display(),
                    humansize::format_size(file_size, BINARY)
                ),
            ),
            (
                "Formats",
                formats
                    .iter()
                    .map(ExportFormat::display_name)
                    .collect::<Vec<_>>()
                    .join(", "),
            ),
            (
                "Output dir",
                output.map_or("exports/".to_string(), |p| p.display().to_string()),
            ),
        ];
        println!("{}", output::kv_table(&pairs));
        println!();
        println!("  {}", output::badge_pass("Plan valid — ready to export"));
    }
    Ok(())
}

/// Run the export plan (dry-run validation).
#[allow(clippy::too_many_arguments, clippy::disallowed_methods)]
fn run_plan(
    file: &Path,
    format: &str,
    output: Option<&Path>,
    quantize: Option<&str>,
    batch: Option<&str>,
    json_output: bool,
) -> Result<()> {
    if !file.exists() {
        return Err(CliError::FileNotFound(file.to_path_buf()));
    }

    let file_size = std::fs::metadata(file).map(|m| m.len()).unwrap_or(0);

    if let Some(batch_formats) = batch {
        return run_plan_batch(
            file,
            file_size,
            batch_formats,
            quantize,
            output,
            json_output,
        );
    }

    let effective_output = output.unwrap_or(Path::new("model.safetensors"));
    let (export_format, quant_type) = resolve_export_options(format, effective_output, quantize)?;

    if json_output {
        let json = serde_json::json!({
            "plan": true,
            "status": "valid",
            "input": file.display().to_string(),
            "input_size": file_size,
            "output": effective_output.display().to_string(),
            "format": export_format.display_name(),
            "quantization": quant_type.as_ref().map(|q| format!("{q:?}")),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        output::header("APR Export — Plan");
        let mut pairs: Vec<(&str, String)> = vec![
            (
                "Input",
                format!(
                    "{} ({})",
                    file.display(),
                    humansize::format_size(file_size, BINARY)
                ),
            ),
            ("Output", effective_output.display().to_string()),
            ("Format", export_format.display_name().to_string()),
        ];
        if let Some(ref q) = quant_type {
            pairs.push(("Quantization", format!("{q:?}")));
        }
        println!("{}", output::kv_table(&pairs));
        println!();
        println!("  {}", output::badge_pass("Plan valid — ready to export"));
    }
    Ok(())
}

/// Run the export command
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_methods)]
#[provable_contracts_macros::contract(
    "apr-cli-operations-v1",
    equation = "mutating_output_contract"
)]
pub(crate) fn run(
    file: Option<&Path>,
    format: &str,
    output: Option<&Path>,
    quantize: Option<&str>,
    list_formats: bool,
    batch: Option<&str>,
    json_output: bool,
    plan: bool,
) -> Result<()> {
    contract_pre_format_conversion_roundtrip!();
    contract_pre_atomic_write_safety!();
    contract_pre_export_roundtrip!();
    contract_pre_export_fidelity!();
    // Handle --list-formats
    if list_formats {
        return run_list_formats(json_output);
    }

    // Require file for all other operations
    let file = file.ok_or_else(|| {
        CliError::ValidationFailed("Model file path required. Usage: apr export <FILE>".to_string())
    })?;

    // Handle --plan mode (validate inputs, no execution)
    if plan {
        return run_plan(file, format, output, quantize, batch, json_output);
    }

    if !file.exists() {
        return Err(CliError::FileNotFound(file.to_path_buf()));
    }

    // Handle --batch mode
    if let Some(batch_formats) = batch {
        return run_batch(file, batch_formats, output, quantize, json_output);
    }

    // Require output for single export
    let output = output.ok_or_else(|| {
        CliError::ValidationFailed("Output path required. Use -o <path>".to_string())
    })?;

    let (export_format, quant_type) = resolve_export_options(format, output, quantize)?;

    // PMAT-261: Detect stdout pipe output (-o - | -o /dev/stdout)
    let pipe_to_stdout = crate::pipe::is_stdout(&output.to_string_lossy());
    if pipe_to_stdout {
        return run_export_to_stdout(file, export_format, quant_type);
    }

    if !json_output {
        output::header("APR Export");
        let mut pairs = vec![
            ("Input", file.display().to_string()),
            ("Output", output.display().to_string()),
            ("Format", export_format.display_name().to_string()),
        ];
        if let Some(ref q) = quant_type {
            pairs.push(("Quantization", format!("{q:?}")));
        }
        println!("{}", output::kv_table(&pairs));
        println!();
        output::pipeline_stage("Exporting", output::StageStatus::Running);
    }

    let result = execute_and_display(file, output, export_format, quant_type, json_output);
    contract_post_format_conversion_roundtrip!(&());
    contract_post_atomic_write_safety!(&());
    contract_post_export_roundtrip!(&());
    contract_post_export_fidelity!(&());
    result
}

/// PMAT-261: Export to stdout — write raw bytes, no ANSI, no status messages.
///
/// Exports to a temporary file, then writes the raw bytes to stdout.
/// All status output is suppressed (binary data on stdout must be clean).
fn run_export_to_stdout(
    file: &Path,
    export_format: ExportFormat,
    quant_type: Option<QuantizationType>,
) -> Result<()> {
    let tmp_dir = std::env::temp_dir();
    let tmp_path = tmp_dir.join(format!("apr-export-{}.bin", std::process::id()));

    let options = ExportOptions {
        format: export_format,
        quantize: quant_type,
        ..Default::default()
    };

    let result = apr_export(file, &tmp_path, options);
    match result {
        Ok(_) => {
            let data = std::fs::read(&tmp_path).map_err(|e| {
                let _ = std::fs::remove_file(&tmp_path);
                CliError::ValidationFailed(format!("Failed to read exported file: {e}"))
            })?;
            let _ = std::fs::remove_file(&tmp_path);
            crate::pipe::write_stdout(&data)
        }
        Err(e) => {
            let _ = std::fs::remove_file(&tmp_path);
            Err(CliError::ValidationFailed(e.to_string()))
        }
    }
}

/// Parse quantization option string
fn parse_quantization(quantize: Option<&str>) -> Result<Option<QuantizationType>> {
    match quantize {
        Some("int8") => Ok(Some(QuantizationType::Int8)),
        Some("int4") => Ok(Some(QuantizationType::Int4)),
        Some("fp16") => Ok(Some(QuantizationType::Fp16)),
        Some("q4k") => Ok(Some(QuantizationType::Q4K)),
        Some(other) => Err(CliError::ValidationFailed(format!(
            "Unknown quantization: {other}. Supported: int8, int4, fp16, q4k"
        ))),
        None => Ok(None),
    }
}

/// List all supported export formats
#[allow(clippy::disallowed_methods)]
fn run_list_formats(json_output: bool) -> Result<()> {
    if json_output {
        let formats: Vec<serde_json::Value> = ExportFormat::all()
            .iter()
            .map(|f| {
                serde_json::json!({
                    "name": f.display_name(),
                    "extension": f.extension(),
                    "supported": f.is_supported(),
                    "parse_aliases": format_aliases(*f),
                })
            })
            .collect();
        let json = serde_json::json!({ "formats": formats });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        output::header("APR Export — Supported Formats");
        println!();
        for f in ExportFormat::all() {
            let status = if f.is_supported() {
                output::badge_pass("supported")
            } else {
                output::badge_info("planned")
            };
            println!(
                "  {:<14} .{:<14} {}",
                f.display_name(),
                f.extension(),
                status
            );
        }
        println!();
        println!(
            "  {} Use --format <name> to select format.",
            output::badge_info("INFO")
        );
    }
    Ok(())
}

/// Get parse aliases for a format
fn format_aliases(f: ExportFormat) -> Vec<String> {
    match f {
        ExportFormat::SafeTensors => vec!["safetensors".into(), "st".into()],
        ExportFormat::Gguf => vec!["gguf".into()],
        ExportFormat::Mlx => vec!["mlx".into()],
        ExportFormat::Onnx => vec!["onnx".into()],
        ExportFormat::OpenVino => vec!["openvino".into(), "ov".into()],
        ExportFormat::CoreMl => vec!["coreml".into(), "mlpackage".into()],
        ExportFormat::TorchScript => vec!["torchscript".into(), "pt".into(), "torch".into()],
    }
}

/// Print batch export summary (JSON or human-readable).
#[allow(clippy::disallowed_methods)]
fn print_batch_summary(
    file: &Path,
    results: &[(&str, String, ExportReport)],
    total_formats: usize,
    json_output: bool,
) {
    if json_output {
        let json_results: Vec<serde_json::Value> = results
            .iter()
            .map(|(name, path, report)| {
                serde_json::json!({
                    "format": name,
                    "output": path,
                    "original_size": report.original_size,
                    "exported_size": report.exported_size,
                    "tensor_count": report.tensor_count,
                })
            })
            .collect();
        let json = serde_json::json!({
            "batch": true,
            "input": file.display().to_string(),
            "results": json_results,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        println!();
        println!(
            "  {} Batch export complete: {}/{} formats",
            output::badge_pass("PASS"),
            results.len(),
            total_formats
        );
    }
}

/// Export a single format in batch mode. Returns Some on success, None on failure.
fn export_single_format(
    fmt: ExportFormat,
    file: &Path,
    out_dir: &Path,
    quant_type: Option<QuantizationType>,
    json_output: bool,
) -> Option<(&'static str, String, ExportReport)> {
    let ext = fmt.extension();
    let out_path = if fmt == ExportFormat::Mlx {
        out_dir.join(format!("model-{ext}"))
    } else {
        out_dir.join(format!("model.{ext}"))
    };

    if let Some(parent) = out_path.parent() {
        if let Err(e) = std::fs::create_dir_all(parent) {
            eprintln!("Cannot create output directory '{}': {e}", parent.display());
            return None;
        }
    }

    let options = ExportOptions {
        format: fmt,
        quantize: quant_type,
        ..Default::default()
    };

    if !json_output {
        output::pipeline_stage(
            &format!("Exporting to {}", fmt.display_name()),
            output::StageStatus::Running,
        );
    }

    match apr_export(file, &out_path, options) {
        Ok(report) => {
            if !json_output {
                println!(
                    "    {}{} ({})",
                    fmt.display_name(),
                    out_path.display(),
                    format_size(report.exported_size, BINARY)
                );
            }
            Some((fmt.display_name(), out_path.display().to_string(), report))
        }
        Err(e) => {
            if !json_output {
                println!(
                    "    {} {}{}",
                    output::badge_fail("FAIL"),
                    fmt.display_name(),
                    e
                );
            }
            None
        }
    }
}

/// Batch export to multiple formats
#[allow(clippy::disallowed_methods)]
fn run_batch(
    file: &Path,
    batch_formats: &str,
    output_dir: Option<&Path>,
    quantize: Option<&str>,
    json_output: bool,
) -> Result<()> {
    let out_dir = output_dir.unwrap_or(Path::new("exports"));

    // Parse comma-separated formats
    let formats: Vec<ExportFormat> = batch_formats
        .split(',')
        .map(|s| {
            s.trim()
                .parse::<ExportFormat>()
                .map_err(|_| CliError::ValidationFailed(format!("Unknown format in batch: {s}")))
        })
        .collect::<Result<Vec<_>>>()?;

    // Validate all are supported
    for f in &formats {
        if !f.is_supported() {
            return Err(CliError::ValidationFailed(format!(
                "Format '{}' in batch is not yet supported",
                f.display_name()
            )));
        }
    }

    let quant_type = parse_quantization(quantize)?;

    if !json_output {
        output::header("APR Export — Batch");
        output::kv("Input", file.display().to_string());
        output::kv("Output dir", out_dir.display().to_string());
        output::kv(
            "Formats",
            formats
                .iter()
                .map(ExportFormat::display_name)
                .collect::<Vec<_>>()
                .join(", "),
        );
        println!();
    }

    let results: Vec<_> = formats
        .iter()
        .filter_map(|&fmt| export_single_format(fmt, file, out_dir, quant_type, json_output))
        .collect();

    print_batch_summary(file, &results, formats.len(), json_output);

    Ok(())
}

/// Display export report (human-readable)
fn display_report(report: &ExportReport) {
    println!();
    output::subheader("Export Report");

    let mut pairs: Vec<(&str, String)> = vec![
        ("Original size", format_size(report.original_size, BINARY)),
        ("Exported size", format_size(report.exported_size, BINARY)),
        ("Tensors", output::count_fmt(report.tensor_count)),
        ("Format", report.format.display_name().to_string()),
    ];
    if let Some(ref quant) = report.quantization {
        pairs.push(("Quantization", format!("{quant:?}")));
    }

    println!("{}", output::kv_table(&pairs));
    println!();
    println!("  {}", output::badge_pass("Export successful"));
}

/// Display export report (JSON)
#[allow(clippy::disallowed_methods)]
fn display_report_json(report: &ExportReport) {
    let json = serde_json::json!({
        "status": "success",
        "original_size": report.original_size,
        "exported_size": report.exported_size,
        "tensor_count": report.tensor_count,
        "format": report.format.display_name(),
        "quantization": report.quantization.as_ref().map(|q| format!("{q:?}")),
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&json).unwrap_or_default()
    );
}

include!("export_file.rs");