anamnesis 0.6.9

Parse any tensor format, recover any precision — framework-agnostic FP8/GPTQ/AWQ/BnB dequantization, NPZ parsing, and PyTorch .pth conversion for Rust
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! CLI smoke tests for `amn convert` — Phase 6 step 2.
//!
//! Spawns the built binary via `std::process::Command` to verify argument
//! parsing, dispatch routing, and end-to-end conversion for each
//! v0.6.0-available target. Pairs with the in-process library-level
//! round-trip suite at `tests/cross_validation_convert.rs` (step 3), which
//! exercises the same conversion paths without the CLI hop.

#![allow(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::as_conversions,
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::same_item_push
)]

use std::process::Command;

/// Locates the built `amn`/`anamnesis` binary. Same shape as
/// `tests/cli.rs::binary_path`.
fn binary_path() -> std::path::PathBuf {
    let mut path = std::env::current_exe()
        .expect("cannot determine test executable path")
        .parent()
        .expect("no parent directory")
        .parent()
        .expect("no grandparent directory")
        .to_path_buf();
    path.push(if cfg!(windows) { "amn.exe" } else { "amn" });
    assert!(
        path.exists(),
        "amn binary not found at {}. Run `cargo build --features cli,npz,pth,gguf,bnb` \
         before `cargo test`.",
        path.display()
    );
    path
}

// ---------------------------------------------------------------------------
// Synthetic fixture builders
// ---------------------------------------------------------------------------

/// Builds a tiny BF16 safetensors file in-memory.
fn build_safetensors_bf16(tensors: &[(&str, &[usize], &[u8])]) -> Vec<u8> {
    let views: Vec<(&str, safetensors::tensor::TensorView<'_>)> = tensors
        .iter()
        .map(|(name, shape, data)| {
            let view = safetensors::tensor::TensorView::new(
                safetensors::Dtype::BF16,
                shape.to_vec(),
                data,
            )
            .unwrap();
            (*name, view)
        })
        .collect();
    safetensors::tensor::serialize(views, None).unwrap()
}

/// Builds a tiny F32 NPZ archive in-memory.
#[cfg(feature = "npz")]
fn build_npz_f32(tensors: &[(&str, &[usize], &[u8])]) -> Vec<u8> {
    use std::io::Write;
    let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::<u8>::new()));
    let options: zip::write::SimpleFileOptions =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    for (name, shape, data) in tensors {
        let entry = format!("{name}.npy");
        zip.start_file(&entry, options).unwrap();
        // Write minimal NPY v1.0 header: magic + version + header_len + dict + padding.
        let shape_str: Vec<String> = shape.iter().map(usize::to_string).collect();
        let shape_tuple = if shape.len() == 1 {
            format!("({},)", shape_str[0])
        } else {
            format!("({})", shape_str.join(", "))
        };
        let dict = format!("{{'descr': '<f4', 'fortran_order': False, 'shape': {shape_tuple}, }}");
        // Header layout: 10 bytes (magic+version+u16 len) + dict + padding + newline,
        // padded to 64-byte boundary.
        let mut header = dict.into_bytes();
        let header_total = 10 + header.len() + 1;
        let pad = (64 - header_total % 64) % 64;
        for _ in 0..pad {
            header.push(b' ');
        }
        header.push(b'\n');
        let header_len_u16 = u16::try_from(header.len()).unwrap();
        let mut entry_bytes: Vec<u8> = Vec::with_capacity(10 + header.len() + data.len());
        entry_bytes.extend_from_slice(&[0x93, b'N', b'U', b'M', b'P', b'Y', 1, 0]);
        entry_bytes.extend_from_slice(&header_len_u16.to_le_bytes());
        entry_bytes.extend_from_slice(&header);
        entry_bytes.extend_from_slice(data);
        zip.write_all(&entry_bytes).unwrap();
    }
    zip.finish().unwrap().into_inner()
}

fn write_temp(bytes: &[u8], ext: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("create temp dir");
    let path = dir.path().join(format!("fixture.{ext}"));
    std::fs::write(&path, bytes).unwrap();
    (dir, path)
}

#[cfg(feature = "bnb")]
fn bf16_bytes_from_f32_iter<I: IntoIterator<Item = f32>>(values: I) -> Vec<u8> {
    let mut out = Vec::new();
    for v in values {
        // BF16 = upper 16 bits of f32 (truncate).
        let bits = (v.to_bits() >> 16) as u16;
        out.extend_from_slice(&bits.to_le_bytes());
    }
    out
}

// ---------------------------------------------------------------------------
// Smoke tests
// ---------------------------------------------------------------------------

#[test]
#[cfg(feature = "npz")]
fn convert_npz_to_safetensors_smokes() {
    let f32_data: Vec<u8> = (0..4u32)
        .flat_map(|i| f32::from(i as u16).to_le_bytes())
        .collect();
    let other: Vec<u8> = (0..6u32)
        .flat_map(|i| (f32::from(i as u16) * 0.5).to_le_bytes())
        .collect();
    let npz_bytes = build_npz_f32(&[("w", &[2, 2], &f32_data), ("b", &[6], &other)]);
    let (_dir, in_path) = write_temp(&npz_bytes, "npz");
    let out_path = in_path.with_extension("safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "safetensors",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert failed\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(out_path.exists(), "output file missing");

    // Re-parse the safetensors output and confirm both tensors landed.
    let bytes = std::fs::read(&out_path).unwrap();
    let parsed = safetensors::SafeTensors::deserialize(&bytes).unwrap();
    let mut names: Vec<&str> = parsed.names();
    names.sort_unstable();
    assert_eq!(names, vec!["b", "w"]);
}

#[test]
#[cfg(feature = "gguf")]
fn convert_safetensors_bf16_to_gguf_smokes() {
    // 8 BF16 elements arranged as [2, 4]
    let bf16: Vec<u8> = (0..8u32)
        .flat_map(|i| {
            let v = i as f32;
            // CAST: u32 -> u16 truncation intentional
            let bits = (v.to_bits() >> 16) as u16;
            bits.to_le_bytes()
        })
        .collect();
    let st_bytes = build_safetensors_bf16(&[("w", &[2, 4], &bf16)]);
    let (_dir, in_path) = write_temp(&st_bytes, "safetensors");
    let out_path = in_path.with_file_name("out.gguf");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "gguf",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert failed\nstdout: {stdout}\nstderr: {stderr}"
    );

    // Re-parse the GGUF output, expect 1 BF16 tensor.
    let parsed = anamnesis::parse_gguf(&out_path).unwrap();
    let info = parsed.inspect();
    assert_eq!(info.tensor_count, 1);
    let collected: Vec<_> = parsed.tensors().collect();
    assert_eq!(collected[0].name, "w");
    assert_eq!(collected[0].dtype, anamnesis::GgufType::BF16);
    // Safetensors shape [2, 4] is row-major, GGUF shape should be reversed [4, 2].
    assert_eq!(collected[0].shape, &[4, 2]);
    assert_eq!(collected[0].data.as_ref(), bf16.as_slice());
}

#[test]
#[cfg(feature = "bnb")]
fn convert_safetensors_bf16_to_bnb_nf4_smokes() {
    // 64 BF16 elements arranged as [64, 1] — exactly one NF4 block of 64.
    let bf16 = bf16_bytes_from_f32_iter((0..64).map(|i| (i as f32 - 31.5) / 32.0));
    let st_bytes = build_safetensors_bf16(&[("linear", &[64, 1], &bf16)]);
    let (_dir, in_path) = write_temp(&st_bytes, "safetensors");
    let out_path = in_path.with_file_name("out-bnb-nf4.safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "bnb-nf4",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert failed\nstdout: {stdout}\nstderr: {stderr}"
    );

    // Re-parse — the safetensors should be classified as Bnb4.
    let model = anamnesis::parse(&out_path).unwrap();
    assert_eq!(model.header.scheme, anamnesis::QuantScheme::Bnb4);
    let names: Vec<&str> = model
        .header
        .tensors
        .iter()
        .map(|t| t.name.as_str())
        .collect();
    assert!(names.contains(&"linear.weight"));
    assert!(names.contains(&"linear.weight.absmax"));
    assert!(names.contains(&"linear.weight.quant_map"));
    assert!(names.contains(&"linear.weight.quant_state.bitsandbytes__nf4"));
}

#[test]
#[cfg(all(feature = "npz", feature = "bnb"))]
fn convert_npz_to_bnb_nf4_smokes() {
    // 64 F32 elements as [64, 1] — exactly one NF4 block. Before Phase 6.14 this
    // pair returned `Unsupported` (the NF4 target accepted only a plain-BF16
    // safetensors source); the BF16 hub now routes NPZ -> BF16 -> NF4 encoder.
    let f32_data: Vec<u8> = (0..64)
        .flat_map(|i| ((i as f32 - 31.5) / 32.0).to_le_bytes())
        .collect();
    let npz_bytes = build_npz_f32(&[("linear", &[64, 1], &f32_data)]);
    let (_dir, in_path) = write_temp(&npz_bytes, "npz");
    let out_path = in_path.with_file_name("out-npz-bnb-nf4.safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "bnb-nf4",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert npz -> bnb-nf4 failed\nstdout: {stdout}\nstderr: {stderr}"
    );

    let model = anamnesis::parse(&out_path).unwrap();
    assert_eq!(model.header.scheme, anamnesis::QuantScheme::Bnb4);
    let names: Vec<&str> = model
        .header
        .tensors
        .iter()
        .map(|t| t.name.as_str())
        .collect();
    assert!(names.contains(&"linear.weight"));
    assert!(names.contains(&"linear.weight.absmax"));
}

/// `.pth` → `bnb-nf4` (Phase 6.14 Step 2) — previously `Unsupported`; the BF16
/// hub now routes it.
///
/// This fixture pins the **passthrough** half of the encoder contract: its three
/// F32 tensors are `[2, 1]`, `[2, 2]`, `[2, 2]` (2–4 elements), all far below the
/// 64-element NF4 block, so none is eligible and every tensor is written through
/// as `BF16` with no NF4 companions. The hub still performs the `F32` → `BF16`
/// conversion the encoder's input contract requires. The *quantising* half of the
/// contract is covered by the NPZ and GGUF cases above, which use 64-element
/// tensors.
#[test]
#[cfg(all(feature = "pth", feature = "bnb"))]
fn convert_pth_to_bnb_nf4_passes_ineligible_tensors_through() {
    let in_path = std::path::Path::new("tests/fixtures/pth_reference/algzoo_rnn_small.pth");
    assert!(in_path.exists(), "committed .pth fixture missing");
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("out-pth-bnb-nf4.safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "bnb-nf4",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert pth -> bnb-nf4 failed\nstdout: {stdout}\nstderr: {stderr}"
    );

    let model = anamnesis::parse(&out_path).unwrap();
    let names: Vec<&str> = model
        .header
        .tensors
        .iter()
        .map(|t| t.name.as_str())
        .collect();
    assert_eq!(names.len(), 3, "all three tensors survive: {names:?}");
    assert!(names.contains(&"rnn.weight_ih_l0"));
    assert!(names.contains(&"rnn.weight_hh_l0"));
    assert!(names.contains(&"linear.weight"));
    // Nothing was eligible, so no NF4 companion tensors were emitted.
    assert!(
        !names.iter().any(|n| n.ends_with(".absmax")),
        "no tensor is NF4-eligible, so none should gain companions: {names:?}"
    );
    // The hub converted F32 -> BF16 on the way to the encoder.
    assert!(
        model
            .header
            .tensors
            .iter()
            .all(|t| t.dtype == anamnesis::Dtype::BF16),
        "passthrough tensors should be BF16"
    );
}

/// `gguf` → `bnb-nf4` (Phase 6.14 Step 2): the hub dequantises/normalises the
/// GGUF source to BF16, then the NF4 encoder runs. GGUF stores dimensions
/// most-significant-first, so `[1, 64]` on disk is `[64, 1]` row-major — exactly
/// one NF4 block.
#[test]
#[cfg(all(feature = "gguf", feature = "bnb"))]
fn convert_gguf_to_bnb_nf4_smokes() {
    use std::collections::HashMap;

    let f32_bytes: Vec<u8> = (0..64)
        .flat_map(|i| ((i as f32 - 31.5) / 32.0).to_le_bytes())
        .collect();
    let shape = [1usize, 64];
    let tensors = [anamnesis::GgufWriteTensor {
        name: "linear",
        shape: &shape,
        dtype: anamnesis::GgufType::F32,
        data: &f32_bytes,
    }];

    let dir = tempfile::tempdir().expect("tempdir");
    let in_path = dir.path().join("in.gguf");
    anamnesis::write_gguf(&in_path, &tensors, &HashMap::new()).expect("write gguf fixture");
    let out_path = dir.path().join("out-gguf-bnb-nf4.safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "bnb-nf4",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "amn convert gguf -> bnb-nf4 failed\nstdout: {stdout}\nstderr: {stderr}"
    );

    let model = anamnesis::parse(&out_path).unwrap();
    assert_eq!(model.header.scheme, anamnesis::QuantScheme::Bnb4);
    let names: Vec<&str> = model
        .header
        .tensors
        .iter()
        .map(|t| t.name.as_str())
        .collect();
    assert!(names.contains(&"linear.weight"));
    assert!(names.contains(&"linear.weight.absmax"));
}

/// `gguf` → `gguf` dequantise-in-place (Phase 6.14 Step 3) must **preserve the
/// source KV**. Re-emitting a GGUF with an empty metadata table would produce a
/// bare tensor container that no inference runtime can load, so the hub carries
/// the source's architecture / hyper-parameter keys into the output.
#[test]
#[cfg(feature = "gguf")]
fn convert_gguf_to_gguf_preserves_metadata() {
    use anamnesis::GgufMetadataValue;
    use std::collections::HashMap;

    let f32_bytes: Vec<u8> = (0..8).flat_map(|i| (i as f32).to_le_bytes()).collect();
    let shape = [8usize];
    let tensors = [anamnesis::GgufWriteTensor {
        name: "w",
        shape: &shape,
        dtype: anamnesis::GgufType::F32,
        data: &f32_bytes,
    }];
    let mut meta: HashMap<String, GgufMetadataValue> = HashMap::new();
    meta.insert(
        "general.architecture".to_owned(),
        GgufMetadataValue::String("llama".to_owned()),
    );
    meta.insert("llama.block_count".to_owned(), GgufMetadataValue::U32(32));

    let dir = tempfile::tempdir().expect("tempdir");
    let in_path = dir.path().join("in.gguf");
    anamnesis::write_gguf(&in_path, &tensors, &meta).expect("write gguf fixture");
    let out_path = dir.path().join("out.gguf");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "gguf",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "amn convert gguf -> gguf failed\nstderr: {stderr}"
    );

    let reparsed = anamnesis::parse_gguf(&out_path).expect("re-parse converted gguf");
    let out_meta = reparsed.metadata();
    assert_eq!(
        out_meta.get("general.architecture"),
        Some(&GgufMetadataValue::String("llama".to_owned())),
        "source architecture KV must survive the round trip: {out_meta:?}"
    );
    assert_eq!(
        out_meta.get("llama.block_count"),
        Some(&GgufMetadataValue::U32(32)),
        "typed numeric KV must survive with its type intact: {out_meta:?}"
    );
}

/// A **quantised** safetensors → `gguf` used to fail with a "dequantise first"
/// error that forced the user to stage a temp file by hand. The hub now chains
/// the two hops internally (Phase 6.14 Step 3).
#[test]
#[cfg(feature = "gguf")]
fn convert_quantized_safetensors_to_gguf_auto_chains() {
    let in_path = std::path::Path::new("tests/fixtures/safetensors_reference/fp8.safetensors");
    assert!(in_path.exists(), "committed FP8 fixture missing");
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("out.gguf");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "gguf",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .output()
        .expect("run amn convert");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "quantised safetensors -> gguf should auto-chain\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        stdout.contains("dequantized to BF16"),
        "expected the chain to report a dequant step, got: {stdout}"
    );

    // The FP8 weight came out as BF16; nothing quantised remains.
    let reparsed = anamnesis::parse_gguf(&out_path).expect("re-parse converted gguf");
    assert!(
        reparsed.tensors().all(|t| !t.dtype.is_quantized()),
        "output GGUF must be scalar (dequantised)"
    );
}

/// `--gguf-metadata` / `--gguf-kv` (Phase 6.14 Step 4) and the precedence chain
/// they form with Step 3's inherited KV: **source KV → JSON file → `--gguf-kv`**,
/// each layer overriding the one before, with untouched source keys surviving.
#[test]
#[cfg(feature = "gguf")]
fn convert_gguf_metadata_flags_merge_over_source_kv() {
    use anamnesis::GgufMetadataValue;
    use std::collections::HashMap;

    let f32_bytes: Vec<u8> = (0..4).flat_map(|i| (i as f32).to_le_bytes()).collect();
    let shape = [4usize];
    let tensors = [anamnesis::GgufWriteTensor {
        name: "w",
        shape: &shape,
        dtype: anamnesis::GgufType::F32,
        data: &f32_bytes,
    }];
    let mut source_meta: HashMap<String, GgufMetadataValue> = HashMap::new();
    source_meta.insert(
        "general.architecture".to_owned(),
        GgufMetadataValue::String("source-arch".to_owned()),
    );
    source_meta.insert(
        "general.name".to_owned(),
        GgufMetadataValue::String("keepme".to_owned()),
    );

    let dir = tempfile::tempdir().expect("tempdir");
    let in_path = dir.path().join("in.gguf");
    anamnesis::write_gguf(&in_path, &tensors, &source_meta).expect("write gguf fixture");

    let meta_path = dir.path().join("meta.json");
    std::fs::write(
        &meta_path,
        r#"{
             "general.architecture": "from-file",
             "llama.block_count": {"type": "u32", "value": 32},
             "tokenizer.ggml.token_type": {"type": "array", "item_type": "i32", "value": [1, 2]}
           }"#,
    )
    .expect("write metadata json");

    let out_path = dir.path().join("out.gguf");
    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "gguf",
            "-o",
            out_path.to_str().unwrap(),
            "--gguf-metadata",
            meta_path.to_str().unwrap(),
            "--gguf-kv",
            "general.architecture=from-flag",
        ])
        .output()
        .expect("run amn convert");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "amn convert with metadata flags failed\nstderr: {stderr}"
    );

    let reparsed = anamnesis::parse_gguf(&out_path).expect("re-parse converted gguf");
    let meta = reparsed.metadata();

    // --gguf-kv beats the JSON file, which beats the inherited source value.
    assert_eq!(
        meta.get("general.architecture"),
        Some(&GgufMetadataValue::String("from-flag".to_owned())),
        "flag should win the three-way merge: {meta:?}"
    );
    // A source key nobody overrode survives (Step 3's inheritance).
    assert_eq!(
        meta.get("general.name"),
        Some(&GgufMetadataValue::String("keepme".to_owned())),
        "untouched source KV must survive: {meta:?}"
    );
    // Typed values from the file keep their declared width.
    assert_eq!(
        meta.get("llama.block_count"),
        Some(&GgufMetadataValue::U32(32))
    );
    assert_eq!(
        meta.get("tokenizer.ggml.token_type"),
        Some(&GgufMetadataValue::Array(Box::new(
            anamnesis::GgufMetadataArray::I32(vec![1, 2])
        ))),
        "the explicit item_type must survive as I32, not the inferred U32"
    );
}

/// A malformed `--gguf-kv` is rejected with a message naming the expected shape,
/// rather than being silently dropped.
#[test]
#[cfg(feature = "gguf")]
fn convert_rejects_malformed_gguf_kv() {
    let bf16: Vec<u8> = vec![0u8; 2];
    let st_bytes = build_safetensors_bf16(&[("w", &[1], &bf16)]);
    let (_dir, in_path) = write_temp(&st_bytes, "safetensors");

    let output = Command::new(binary_path())
        .args([
            "convert",
            in_path.to_str().unwrap(),
            "--to",
            "gguf",
            "--gguf-kv",
            "no-equals-sign",
        ])
        .output()
        .expect("run amn convert");
    assert!(
        !output.status.success(),
        "should reject malformed --gguf-kv"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("key=value"),
        "expected a `key=value` hint, got stderr: {stderr}"
    );
}

#[test]
fn convert_unknown_target_errors_cleanly() {
    let bf16: Vec<u8> = vec![0u8; 2];
    let st_bytes = build_safetensors_bf16(&[("w", &[1], &bf16)]);
    let (_dir, in_path) = write_temp(&st_bytes, "safetensors");

    let output = Command::new(binary_path())
        .args(["convert", in_path.to_str().unwrap(), "--to", "frobnicate"])
        .output()
        .expect("run amn convert");
    assert!(!output.status.success(), "should reject unknown target");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("supported convert targets"),
        "expected target-list error, got stderr: {stderr}"
    );
}