apr-cli 0.60.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
use super::*;
use std::collections::HashMap;
use std::io::Write;
use tempfile::{tempdir, NamedTempFile};

// ========================================================================
// Path Validation Tests
// ========================================================================

#[test]
fn test_validate_path_not_found() {
    let result = validate_path(Path::new("/nonexistent/model.apr"));
    assert!(result.is_err());
    match result {
        Err(CliError::FileNotFound(_)) => {}
        _ => panic!("Expected FileNotFound error"),
    }
}

#[test]
fn test_validate_path_is_directory() {
    let dir = tempdir().expect("create temp dir");
    let result = validate_path(dir.path());
    assert!(result.is_err());
    match result {
        Err(CliError::NotAFile(_)) => {}
        _ => panic!("Expected NotAFile error"),
    }
}

#[test]
fn test_validate_path_valid_file() {
    let file = NamedTempFile::new().expect("create temp file");
    let result = validate_path(file.path());
    assert!(result.is_ok());
}

// ========================================================================
// Run Command Tests
// ========================================================================

#[test]
fn test_run_file_not_found() {
    let result = run(
        Path::new("/nonexistent/model.apr"),
        false,
        false,
        None,
        false,
        false,
    );
    assert!(result.is_err());
    match result {
        Err(CliError::FileNotFound(_)) => {}
        _ => panic!("Expected FileNotFound error"),
    }
}

#[test]
fn test_run_is_directory() {
    let dir = tempdir().expect("create temp dir");
    let result = run(dir.path(), false, false, None, false, false);
    assert!(result.is_err());
    match result {
        Err(CliError::NotAFile(_)) => {}
        _ => panic!("Expected NotAFile error"),
    }
}

#[test]
fn test_run_invalid_file() {
    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(b"not a valid APR file").expect("write");

    let result = run(file.path(), false, false, None, false, false);
    // Should fail validation because file is not valid APR
    assert!(result.is_err());
}

#[test]
fn test_run_with_quality_flag() {
    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(b"invalid data").expect("write");

    let result = run(file.path(), true, false, None, false, false);
    // Should fail but quality flag is handled
    assert!(result.is_err());
}

#[test]
fn test_run_with_min_score() {
    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(b"invalid data").expect("write");

    let result = run(file.path(), false, false, Some(100), false, false);
    // Should fail before min_score check because file is invalid
    assert!(result.is_err());
}

#[test]
fn test_run_with_strict_flag() {
    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(b"test data").expect("write");

    let result = run(file.path(), false, true, None, false, false);
    // Should fail with strict mode
    assert!(result.is_err());
}

#[test]
fn test_run_with_all_flags() {
    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(b"test data").expect("write");

    let result = run(file.path(), true, true, Some(50), false, false);
    // Should fail with all flags enabled
    assert!(result.is_err());
}

#[test]
fn test_run_empty_file() {
    let file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    // Empty file - no write

    let result = run(file.path(), false, false, None, false, false);
    // Empty file should fail validation
    assert!(result.is_err());
}

// ========================================================================
// Category Score Tests (using mocked reports via AprValidator)
// ========================================================================

#[test]
fn test_quality_assessment_display() {
    let mut category_scores = HashMap::new();
    category_scores.insert(Category::Structure, 25);
    category_scores.insert(Category::Physics, 20);
    category_scores.insert(Category::Tooling, 15);
    category_scores.insert(Category::Conversion, 10);

    let report = ValidationReport {
        checks: Vec::new(),
        total_score: 70,
        category_scores,
    };

    // Should not panic
    print_quality_assessment(&report);
}

#[test]
fn test_quality_assessment_missing_categories() {
    let report = ValidationReport {
        checks: Vec::new(),
        total_score: 0,
        category_scores: HashMap::new(),
    };

    // Should handle missing categories gracefully (default to 0)
    print_quality_assessment(&report);
}

#[test]
fn test_quality_assessment_all_score_ranges() {
    // High scores
    let mut high_scores = HashMap::new();
    high_scores.insert(Category::Structure, 25);
    high_scores.insert(Category::Physics, 25);
    high_scores.insert(Category::Tooling, 25);
    high_scores.insert(Category::Conversion, 25);

    let high_report = ValidationReport {
        checks: Vec::new(),
        total_score: 100,
        category_scores: high_scores,
    };

    // Low scores
    let mut low_scores = HashMap::new();
    low_scores.insert(Category::Structure, 5);

    let low_report = ValidationReport {
        checks: Vec::new(),
        total_score: 5,
        category_scores: low_scores,
    };

    // All should display without panic
    print_quality_assessment(&high_report);
    print_quality_assessment(&low_report);
}

// ========================================================================
// Print Summary Tests
// ========================================================================

#[test]
fn test_print_summary_valid_report() {
    let report = ValidationReport {
        checks: Vec::new(), // No failed checks
        total_score: 100,
        category_scores: HashMap::new(),
    };

    let result = print_summary(&report);
    assert!(result.is_ok());
}

#[test]
fn test_print_quality_assessment_empty() {
    let report = ValidationReport {
        checks: Vec::new(),
        total_score: 0,
        category_scores: HashMap::new(),
    };

    // Should not panic even with empty report
    print_quality_assessment(&report);
}

// ========================================================================
// Multi-Format Dispatch Tests (GGUF, SafeTensors)
// ========================================================================

#[test]
fn test_run_gguf_format_dispatch() {
    use aprender::format::gguf::{export_tensors_to_gguf, GgmlType, GgufTensor, GgufValue};

    // Create valid GGUF file with non-zero tensor data
    let floats: Vec<f32> = (0..16).map(|i| (i as f32 + 1.0) * 0.1).collect();
    let data: Vec<u8> = floats.iter().flat_map(|f| f.to_le_bytes()).collect();
    let tensor = GgufTensor {
        name: "model.weight".to_string(),
        shape: vec![4, 4],
        dtype: GgmlType::F32,
        data,
    };
    let metadata = vec![(
        "general.architecture".to_string(),
        GgufValue::String("test".to_string()),
    )];

    let mut gguf_bytes = Vec::new();
    export_tensors_to_gguf(&mut gguf_bytes, &[tensor], &metadata).expect("export GGUF");

    let mut file = NamedTempFile::with_suffix(".gguf").expect("create temp file");
    file.write_all(&gguf_bytes).expect("write GGUF");

    // Should dispatch to GGUF validation path (RosettaStone::validate)
    let result = run(file.path(), false, false, None, false, false);
    // GGUF validation should succeed (physics constraints pass)
    assert!(result.is_ok(), "GGUF format dispatch should work");
}

#[test]
fn test_run_safetensors_format_dispatch() {
    // Create valid SafeTensors file manually
    let header_json = serde_json::json!({
        "test.weight": {
            "dtype": "F32",
            "shape": [2, 2],
            "data_offsets": [0, 16]
        }
    });
    let header_bytes = serde_json::to_vec(&header_json).expect("serialize header");
    let header_len = header_bytes.len() as u64;

    let mut st_bytes = Vec::new();
    st_bytes.extend_from_slice(&header_len.to_le_bytes());
    st_bytes.extend_from_slice(&header_bytes);
    // Add valid tensor data (4 floats = 16 bytes)
    let floats: [f32; 4] = [1.0, 2.0, 3.0, 4.0];
    for f in floats {
        st_bytes.extend_from_slice(&f.to_le_bytes());
    }

    let mut file = NamedTempFile::with_suffix(".safetensors").expect("create temp file");
    file.write_all(&st_bytes).expect("write SafeTensors");

    // Should dispatch to SafeTensors validation path (RosettaStone::validate)
    let result = run(file.path(), false, false, None, false, false);
    // SafeTensors validation should succeed
    assert!(result.is_ok(), "SafeTensors format dispatch should work");
}

#[test]
fn test_run_gguf_format_detection_by_magic() {
    use aprender::format::gguf::{export_tensors_to_gguf, GgmlType, GgufTensor, GgufValue};

    // Create GGUF with .bin extension (magic detection, not extension)
    // Use valid non-zero tensor data
    let floats: [f32; 4] = [1.0, 2.0, 3.0, 4.0];
    let tensor_data: Vec<u8> = floats.iter().flat_map(|f| f.to_le_bytes()).collect();

    let tensor = GgufTensor {
        name: "test.weight".to_string(),
        shape: vec![2, 2],
        dtype: GgmlType::F32,
        data: tensor_data,
    };
    let metadata = vec![(
        "general.architecture".to_string(),
        GgufValue::String("test".to_string()),
    )];

    let mut gguf_bytes = Vec::new();
    export_tensors_to_gguf(&mut gguf_bytes, &[tensor], &metadata).expect("export GGUF");

    let mut file = NamedTempFile::with_suffix(".bin").expect("create temp file");
    file.write_all(&gguf_bytes).expect("write GGUF");

    // Should detect GGUF by magic bytes, not extension
    let result = run(file.path(), false, false, None, false, false);
    assert!(result.is_ok(), "Should detect GGUF by magic bytes");
}

#[test]
fn test_run_gguf_with_physics_violations() {
    use aprender::format::gguf::{export_tensors_to_gguf, GgmlType, GgufTensor, GgufValue};

    // Create GGUF with NaN values (physics violation)
    let nan_f32 = f32::NAN.to_le_bytes();
    let mut tensor_data = Vec::new();
    for _ in 0..4 {
        tensor_data.extend_from_slice(&nan_f32);
    }

    let tensor = GgufTensor {
        name: "model.weight".to_string(),
        shape: vec![2, 2],
        dtype: GgmlType::F32,
        data: tensor_data,
    };
    let metadata = vec![(
        "general.architecture".to_string(),
        GgufValue::String("test".to_string()),
    )];

    let mut gguf_bytes = Vec::new();
    export_tensors_to_gguf(&mut gguf_bytes, &[tensor], &metadata).expect("export GGUF");

    let mut file = NamedTempFile::with_suffix(".gguf").expect("create temp file");
    file.write_all(&gguf_bytes).expect("write GGUF");

    // Should fail due to NaN physics violation
    let result = run(file.path(), false, false, None, false, false);
    assert!(result.is_err(), "Should fail with NaN tensors");
}

// ========================================================================
// PMAT-926: APR fail-closed content gates + --strict wiring
//
// Contract: apr-validate-fail-closed-v1.yaml
//   - F-VALIDATE-APR-DISPATCH-001 (content-broken .apr REJECTED)
//   - F-VALIDATE-STRICT-001        (--strict escalates warn → non-zero exit)
//
// Before PMAT-926 the `.apr` path routed to the stubbed `AprValidator`
// (magic/header/version/flags only) and `--strict` printed
// "not yet implemented, flag ignored" — so a semantically-broken `.apr`
// (all-zero lm_head, NaN/Inf, constant weight) was reported VALID and ran
// silently, exactly the class of garbage llama.cpp / Ollama load and run.
// These falsifiers go RED on the stub and GREEN on the fix; a valid model
// still passes (no false positives).
// ========================================================================

/// Build a syntactically-valid `.apr` file from `(name, shape, data)` tensors.
/// Header checksum + offsets are computed by `AprV2Writer`, so the file is a
/// genuinely-parseable model — only the *content* of the tensors varies.
fn write_apr_fixture(tensors: &[(&str, Vec<usize>, Vec<f32>)]) -> NamedTempFile {
    use aprender::format::v2::{AprV2Metadata, AprV2Writer};

    let metadata = AprV2Metadata::new("test");
    let mut writer = AprV2Writer::new(metadata);
    for (name, shape, data) in tensors {
        writer.add_tensor_f32_owned(*name, shape.clone(), data.clone());
    }
    let mut apr_bytes = Vec::new();
    writer.write_to(&mut apr_bytes).expect("write APR fixture");

    let mut file = NamedTempFile::with_suffix(".apr").expect("create temp file");
    file.write_all(&apr_bytes).expect("write apr bytes");
    file
}

/// A healthy weight column with variation (passes all data-quality gates).
fn healthy_weights(n: usize) -> Vec<f32> {
    (0..n).map(|i| ((i as f32) * 0.013 - 0.5) * 0.2).collect()
}

/// FALSIFIER (F-VALIDATE-APR-DISPATCH-001): a valid-header `.apr` whose
/// `lm_head.weight` is entirely zero must be REJECTED. RED on the stub
/// (`AprValidator` never inspects tensor content → returns VALID), GREEN
/// after re-routing through the Rosetta content gates.
#[test]
fn pmat926_falsifier_all_zero_lm_head_apr_rejected() {
    // 8x4 lm_head, every weight zero (dead model). 4x4 healthy embed so the
    // file is otherwise well-formed.
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], vec![0.0; 32]),
        ("model.embed_tokens.weight", vec![4, 4], healthy_weights(16)),
    ]);

    let result = run(file.path(), false, false, None, false, false);
    assert!(
        result.is_err(),
        "all-zero lm_head .apr must be REJECTED (F-VALIDATE-APR-DISPATCH-001), got Ok"
    );
}

/// FALSIFIER (F-VALIDATE-APR-DISPATCH-001): a `.apr` with NaN weights is
/// REJECTED. The incumbents load and run NaN weights silently.
#[test]
fn pmat926_falsifier_nan_tensor_apr_rejected() {
    let mut nan_block = healthy_weights(32);
    nan_block[5] = f32::NAN;
    nan_block[17] = f32::NAN;
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], healthy_weights(32)),
        ("model.layers.0.mlp.down_proj.weight", vec![8, 4], nan_block),
    ]);

    let result = run(file.path(), false, false, None, false, false);
    assert!(
        result.is_err(),
        "NaN .apr must be REJECTED (F-VALIDATE-APR-DISPATCH-001), got Ok"
    );
}

/// NO-FALSE-POSITIVE: a healthy `.apr` (varied, non-zero, finite weights)
/// must still validate clean. Guards the fail-closed gate against rejecting
/// good models.
#[test]
fn pmat926_valid_apr_still_passes() {
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], healthy_weights(32)),
        ("model.embed_tokens.weight", vec![8, 4], healthy_weights(32)),
        (
            "model.layers.0.mlp.down_proj.weight",
            vec![8, 4],
            healthy_weights(32),
        ),
    ]);

    let result = run(file.path(), false, false, None, false, false);
    assert!(
        result.is_ok(),
        "healthy .apr must still PASS (no false positives), got {result:?}"
    );
}

/// FALSIFIER (F-VALIDATE-STRICT-001): `--strict` escalates a warn-level
/// finding to a hard non-zero exit on the `.apr` path. Before PMAT-926
/// `--strict` was a documented no-op for APR ("flag ignored").
#[test]
fn pmat926_falsifier_strict_apr_all_zero_nonzero_exit() {
    // A standalone all-zero tensor (not an output-projection role) lands in
    // `all_zero_tensors` — a strict-blocking finding.
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], healthy_weights(32)),
        (
            "model.layers.0.self_attn.q_proj.bias",
            vec![8],
            vec![0.0; 8],
        ),
    ]);

    // strict = true must fail closed.
    let strict_result = run(file.path(), false, true, None, false, false);
    assert!(
        strict_result.is_err(),
        "--strict on an all-zero-tensor .apr must exit non-zero (F-VALIDATE-STRICT-001), got Ok"
    );
}

/// `--skip-contract` bypasses the fail-closed content gate (parity with the
/// GGUF/SafeTensors path) — a broken `.apr` is accepted when the operator
/// explicitly opts out.
#[test]
fn pmat926_skip_contract_bypasses_content_gate() {
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], vec![0.0; 32]),
        ("model.embed_tokens.weight", vec![4, 4], healthy_weights(16)),
    ]);

    let result = run(
        file.path(),
        false,
        false,
        None,
        false,
        /* skip_contract */ true,
    );
    assert!(
        result.is_ok(),
        "--skip-contract must bypass the content gate, got {result:?}"
    );
}

/// JSON path also fails closed on a content-broken `.apr` (the report is
/// still printed, but the exit code is non-zero).
#[test]
fn pmat926_json_apr_all_zero_lm_head_rejected() {
    let file = write_apr_fixture(&[
        ("lm_head.weight", vec![8, 4], vec![0.0; 32]),
        ("model.embed_tokens.weight", vec![4, 4], healthy_weights(16)),
    ]);

    let result = run(file.path(), false, false, None, /* json */ true, false);
    assert!(
        result.is_err(),
        "JSON .apr path must fail closed on content-broken model, got Ok"
    );
}