cortiq-cli 0.9.27

Command-line tools for the CMF model format: inspect, convert, run and serve .cmf models.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! Recursive Flint compatibility repair.
//!
//! The first public CMF exports of RecursiveSI/flint predated its complete
//! attention profile.  Their quantized tensors are sound, but their headers
//! lack the sliding-window, no-RoPE, learned-sink, and sigmoid-router
//! declarations.  Re-exporting from the 80 GB BF16 source is wasteful and
//! unnecessary: this module validates the exact released tensor catalogue and
//! atomically appends a corrected header.  The directory and every payload
//! byte remain untouched.
//!
//! Flint 1.1 (RecursiveSI/flint-v1.1) is a new post-training of the same base:
//! the architecture, catalogue and execution contract are identical and only
//! the weights differ.  A file's release therefore lives in its provenance,
//! and every rewrite here keeps it instead of stamping the first release.

use anyhow::{Context, bail, ensure};
use cortiq_core::{CmfHeader, CmfModel, LayerType, TensorDtype};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::Path;

/// A reviewed Recursive Flint source release: the Hugging Face repo and the
/// immutable commit a streamed `cortiq convert` reads it at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FlintRelease {
    pub(crate) repo: &'static str,
    pub(crate) revision: &'static str,
}

/// Every release shares one catalogue; the first entry is the original one,
/// the only release that existed when exports without Flint metadata were made.
const FLINT_RELEASES: [FlintRelease; 2] = [
    FlintRelease {
        repo: "RecursiveSI/flint",
        revision: "2a247be0c0aec895ccb0ac7ca92229ec6df37288",
    },
    FlintRelease {
        repo: "RecursiveSI/flint-v1.1",
        revision: "db1fdc0fbffecf3b1df4fa2b0d44b75e5237e469",
    },
];
pub(crate) const FLINT_LAYERS: usize = 49;
const FLINT_TENSORS: usize = 36_734;
pub(crate) const FLINT_HIDDEN: usize = 2_048;
const FLINT_Q_HEADS: usize = 32;
const FLINT_KV_HEADS: usize = 4;
const FLINT_HEAD_DIM: usize = 128;
const FLINT_VOCAB: usize = 150_144;
pub(crate) const FLINT_EXPERTS: usize = 256;
const FLINT_TOP_K: usize = 6;
pub(crate) const FLINT_EXPERT_WIDTH: usize = 512;
const FLINT_SHARED_WIDTH: usize = 1_024;
const FLINT_WINDOW: usize = 513;
const FLINT_NO_ROPE: [usize; 14] = [0, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 48];

/// Recursive's release settings.  These belong in the artifact rather than
/// only in its model card: `run` and `serve` consume `provenance.sampling`,
/// while callers can still explicitly override any field per request.
pub(crate) fn flint_sampling() -> Value {
    json!({
        "temperature": 1.0,
        "top_p": 0.95,
        "top_k": 20,
    })
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum QuantProfile {
    Q4tp,
    Q2tp,
    /// Whole routed gate/up layers may be q2tp or q4tp, but a layer may not
    /// mix them.  This is the only mixed layout the token/decode graph can
    /// dispatch without crossing a per-layer kernel ABI.
    Hybrid,
}

impl QuantProfile {
    pub(crate) fn name(self) -> &'static str {
        match self {
            Self::Q4tp => "q4tp",
            Self::Q2tp => "q2tp",
            Self::Hybrid => "q2tp-q4tp-layer-hybrid",
        }
    }
}

#[derive(Clone, Debug)]
struct RepairPlan {
    profile: QuantProfile,
    release: FlintRelease,
    provenance: Value,
    already_current: bool,
}

fn expected_no_rope() -> Vec<bool> {
    (0..FLINT_LAYERS)
        .map(|li| FLINT_NO_ROPE.contains(&li))
        .collect()
}

fn expected_layer_types() -> Vec<LayerType> {
    expected_no_rope()
        .into_iter()
        .map(|no_rope| {
            if no_rope {
                LayerType::FullAttention
            } else {
                LayerType::SlidingAttention
            }
        })
        .collect()
}

/// Validate the architecture fields shared by both the old and corrected
/// public exports.  This deliberately happens before an in-place update: a
/// similarly named model must never receive Flint semantics by accident.
fn validate_flint_header(header: &CmfHeader) -> anyhow::Result<()> {
    let arch = &header.arch;
    ensure!(
        arch.arch_name == "flint",
        "repair-flint only accepts arch_name=flint (got '{}')",
        arch.arch_name
    );
    ensure!(
        (
            arch.num_layers,
            arch.hidden_size,
            arch.num_attention_heads,
            arch.num_kv_heads,
            arch.head_dim,
            arch.vocab_size
        ) == (
            FLINT_LAYERS,
            FLINT_HIDDEN,
            FLINT_Q_HEADS,
            FLINT_KV_HEADS,
            FLINT_HEAD_DIM,
            FLINT_VOCAB
        ),
        "Flint geometry is not the released RecursiveSI/flint profile"
    );
    ensure!(
        arch.layer_types == expected_layer_types(),
        "Flint layer schedule is not the released 35 sliding / 14 full schedule"
    );
    let moe = arch
        .moe
        .as_ref()
        .context("Flint header has no MoE descriptor")?;
    ensure!(
        (
            moe.num_experts,
            moe.top_k,
            moe.moe_intermediate_size,
            moe.shared_expert_intermediate_size
        ) == (
            FLINT_EXPERTS,
            FLINT_TOP_K,
            FLINT_EXPERT_WIDTH,
            Some(FLINT_SHARED_WIDTH)
        ),
        "Flint MoE geometry is not 256 experts / top-6 / 512 + shared-1024"
    );
    ensure!(
        moe.norm_topk_prob,
        "Flint must normalize its selected sigmoid routing scores"
    );
    Ok(())
}

/// The reviewed release whose Hugging Face repo id is `repo` (ids compare
/// case-insensitively, as the Hub resolves them).
pub(crate) fn release_for_repo(repo: &str) -> Option<FlintRelease> {
    FLINT_RELEASES
        .iter()
        .copied()
        .find(|release| release.repo.eq_ignore_ascii_case(repo))
}

fn release_names() -> String {
    FLINT_RELEASES
        .iter()
        .map(|release| release.repo)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Whether the header already declares Flint's execution semantics, i.e. it
/// was written by a converter that knows Flint (0.8.29 and later).
fn has_flint_semantics(header: &CmfHeader) -> bool {
    let arch = &header.arch;
    arch.sliding_window.is_some()
        || arch.no_rope_layers.is_some()
        || arch.attention_sink
        || arch.moe.as_ref().is_some_and(|moe| moe.router_sigmoid)
}

/// Which Flint release a CMF holds, from its provenance.  A recorded repo id
/// or revision decides; a file with neither is accepted only as an export
/// that predates Flint metadata, which can only be the original release.  A
/// file written by a Flint-aware converter without either is refused rather
/// than labelled with a guessed release.
fn release_of(header: &CmfHeader) -> anyhow::Result<FlintRelease> {
    let provenance = header.provenance.as_ref().and_then(Value::as_object);
    let field = |key: &str| {
        provenance
            .and_then(|p| p.get(key))
            .and_then(Value::as_str)
    };
    let revision = field("source_revision");
    if let Some(release) = field("source_model").and_then(release_for_repo) {
        if let Some(revision) = revision {
            ensure!(
                revision == release.revision,
                "CMF records {} at revision {revision}, not the reviewed revision {}",
                release.repo,
                release.revision
            );
        }
        return Ok(release);
    }
    if let Some(revision) = revision {
        return FLINT_RELEASES
            .iter()
            .copied()
            .find(|release| release.revision == revision)
            .with_context(|| {
                format!(
                    "Flint source revision {revision} is not a reviewed release of {}",
                    release_names()
                )
            });
    }
    ensure!(
        !has_flint_semantics(header),
        "cannot tell which Flint release this CMF holds: its provenance names neither {} \
         nor a reviewed revision; convert from the Hugging Face repo id",
        release_names()
    );
    Ok(FLINT_RELEASES[0])
}

pub(crate) fn expert_name(li: usize, expert: usize, leaf: &str) -> String {
    format!("model.layers.{li}.mlp.experts.{expert}.{leaf}.weight")
}

/// Remove one exactly-shaped directory entry from a catalogue under
/// validation.  Removing every expected name and rejecting leftovers means a
/// same-length but structurally different CMF cannot be blessed as Flint.
fn take_catalogue_entry<'a>(
    remaining: &mut HashMap<&'a str, &'a cortiq_core::TensorEntry>,
    name: &str,
    shape: &[usize],
    allowed_dtypes: &[TensorDtype],
) -> anyhow::Result<&'a cortiq_core::TensorEntry> {
    let entry = remaining
        .remove(name)
        .with_context(|| format!("missing Flint tensor '{name}'"))?;
    ensure!(
        entry.shape.as_slice() == shape,
        "{name} has shape {:?}, expected {shape:?}",
        entry.shape
    );
    ensure!(
        allowed_dtypes.contains(&entry.dtype),
        "{name} has dtype {:?}, expected one of {:?}",
        entry.dtype,
        allowed_dtypes
    );
    Ok(entry)
}

/// Validate every name, shape, and non-profile dtype in Flint's released
/// catalogue.  The two routed gate/up matrices are deliberately the only
/// entries allowed to be q2tp or q4tp; their per-layer profile is returned.
fn validate_flint_catalogue(
    tensors: &[cortiq_core::TensorEntry],
) -> anyhow::Result<Vec<TensorDtype>> {
    ensure!(
        tensors.len() == FLINT_TENSORS,
        "Flint tensor catalogue has {} entries, expected {FLINT_TENSORS}",
        tensors.len()
    );
    let mut remaining = HashMap::with_capacity(tensors.len());
    for entry in tensors {
        ensure!(
            remaining.insert(entry.name.as_str(), entry).is_none(),
            "Flint tensor catalogue has duplicate entry '{}'",
            entry.name
        );
    }

    let f16 = [TensorDtype::F16];
    let q4tp = [TensorDtype::Q4TiledP];
    let routed = [TensorDtype::Q2TiledP, TensorDtype::Q4TiledP];

    take_catalogue_entry(
        &mut remaining,
        "model.embed_tokens.weight",
        &[FLINT_VOCAB, FLINT_HIDDEN],
        &q4tp,
    )?;
    take_catalogue_entry(&mut remaining, "model.norm.weight", &[FLINT_HIDDEN], &f16)?;
    take_catalogue_entry(
        &mut remaining,
        "lm_head.weight",
        &[FLINT_VOCAB, FLINT_HIDDEN],
        &q4tp,
    )?;

    let mut layer_profiles = Vec::with_capacity(FLINT_LAYERS.saturating_sub(2));
    for li in 0..FLINT_LAYERS {
        let prefix = format!("model.layers.{li}");
        for (suffix, shape, allowed_dtypes) in [
            ("input_layernorm.weight", vec![FLINT_HIDDEN], &f16[..]),
            (
                "post_attention_layernorm.weight",
                vec![FLINT_HIDDEN],
                &f16[..],
            ),
            ("self_attn.q_norm.weight", vec![FLINT_HEAD_DIM], &f16[..]),
            ("self_attn.k_norm.weight", vec![FLINT_HEAD_DIM], &f16[..]),
            (
                "self_attn.q_proj.weight",
                vec![FLINT_Q_HEADS * FLINT_HEAD_DIM, FLINT_HIDDEN],
                &q4tp[..],
            ),
            (
                "self_attn.k_proj.weight",
                vec![FLINT_KV_HEADS * FLINT_HEAD_DIM, FLINT_HIDDEN],
                &q4tp[..],
            ),
            (
                "self_attn.v_proj.weight",
                vec![FLINT_KV_HEADS * FLINT_HEAD_DIM, FLINT_HIDDEN],
                &q4tp[..],
            ),
            (
                "self_attn.o_proj.weight",
                vec![FLINT_HIDDEN, FLINT_Q_HEADS * FLINT_HEAD_DIM],
                &q4tp[..],
            ),
            ("self_attn.softmax_offset", vec![FLINT_Q_HEADS], &f16[..]),
        ] {
            take_catalogue_entry(
                &mut remaining,
                &format!("{prefix}.{suffix}"),
                &shape,
                allowed_dtypes,
            )?;
        }

        if li < 2 {
            for (suffix, shape) in [
                ("mlp.gate_proj.weight", vec![6_144, FLINT_HIDDEN]),
                ("mlp.up_proj.weight", vec![6_144, FLINT_HIDDEN]),
                ("mlp.down_proj.weight", vec![FLINT_HIDDEN, 6_144]),
            ] {
                take_catalogue_entry(&mut remaining, &format!("{prefix}.{suffix}"), &shape, &q4tp)?;
            }
            continue;
        }

        take_catalogue_entry(
            &mut remaining,
            &format!("{prefix}.mlp.gate.weight"),
            &[FLINT_EXPERTS, FLINT_HIDDEN],
            &f16,
        )?;
        for (suffix, shape) in [
            ("gate_proj.weight", vec![FLINT_SHARED_WIDTH, FLINT_HIDDEN]),
            ("up_proj.weight", vec![FLINT_SHARED_WIDTH, FLINT_HIDDEN]),
            ("down_proj.weight", vec![FLINT_HIDDEN, FLINT_SHARED_WIDTH]),
        ] {
            take_catalogue_entry(
                &mut remaining,
                &format!("{prefix}.mlp.shared_expert.{suffix}"),
                &shape,
                &q4tp,
            )?;
        }

        let mut layer_dtype = None;
        for expert in 0..FLINT_EXPERTS {
            for leaf in ["gate_proj", "up_proj"] {
                let name = expert_name(li, expert, leaf);
                let entry = take_catalogue_entry(
                    &mut remaining,
                    &name,
                    &[FLINT_EXPERT_WIDTH, FLINT_HIDDEN],
                    &routed,
                )?;
                if let Some(expected) = layer_dtype {
                    ensure!(
                        entry.dtype == expected,
                        "Flint routed layer {li} mixes q4tp and q2tp gate/up tensors; \
                         {name} is {:?}, expected {:?}",
                        entry.dtype,
                        expected
                    );
                } else {
                    layer_dtype = Some(entry.dtype);
                }
            }
            let name = expert_name(li, expert, "down_proj");
            take_catalogue_entry(
                &mut remaining,
                &name,
                &[FLINT_HIDDEN, FLINT_EXPERT_WIDTH],
                &q4tp,
            )?;
        }
        layer_profiles.push(layer_dtype.expect("each routed Flint layer has gate/up tensors"));
    }

    ensure!(
        remaining.is_empty(),
        "Flint tensor catalogue contains unexpected entry '{}'{}, not part of the released profile",
        remaining.keys().next().expect("checked non-empty"),
        if remaining.len() > 1 {
            " (and others)"
        } else {
            ""
        }
    );
    Ok(layer_profiles)
}

/// Verify the actual release catalogue, then derive its profile from tensor
/// dtypes rather than trusting stale header provenance.
pub(crate) fn inspect_quant_profile(model: &CmfModel) -> anyhow::Result<QuantProfile> {
    validate_flint_header(&model.header)?;
    profile_from_layer_dtypes(&validate_flint_catalogue(&model.tensors)?)
}

/// Classify an already uniform routed layer sequence.  Keeping this separate
/// makes it explicit that Hybrid is a *layer* property, not permission for an
/// arbitrary mixture of individual expert tensors.
fn profile_from_layer_dtypes(layer_dtypes: &[TensorDtype]) -> anyhow::Result<QuantProfile> {
    let mut seen_q4 = false;
    let mut seen_q2 = false;
    for &dtype in layer_dtypes {
        match dtype {
            TensorDtype::Q4TiledP => seen_q4 = true,
            TensorDtype::Q2TiledP => seen_q2 = true,
            other => bail!("Flint routed layer must be q4tp or q2tp, got {other:?}"),
        }
    }
    match (seen_q4, seen_q2) {
        (true, false) => Ok(QuantProfile::Q4tp),
        (false, true) => Ok(QuantProfile::Q2tp),
        (true, true) => Ok(QuantProfile::Hybrid),
        (false, false) => bail!("Flint contains no routed gate/up tensors"),
    }
}

fn repaired_provenance(
    old: Option<&Value>,
    profile: QuantProfile,
    release: FlintRelease,
) -> anyhow::Result<Value> {
    let mut provenance = old.cloned().unwrap_or_else(|| json!({}));
    let object = provenance
        .as_object_mut()
        .context("Flint provenance must be a JSON object when present")?;
    object.insert("source_model".into(), json!(release.repo));
    object.insert("source_revision".into(), json!(release.revision));
    object.insert("weight_quant".into(), json!(profile.name()));
    object.insert("sampling".into(), flint_sampling());
    object.insert(
        "flint_repair".into(),
        json!({
            "kind": "header-only",
            "reason": "restore sliding-window, no-RoPE, learned-sink, and sigmoid-router metadata",
            "source_revision": release.revision,
            "tensor_payloads": "unchanged",
        }),
    );
    Ok(provenance)
}

fn has_current_metadata(header: &CmfHeader, profile: QuantProfile) -> bool {
    let arch = &header.arch;
    let Some(moe) = arch.moe.as_ref() else {
        return false;
    };
    let Ok(release) = release_of(header) else {
        return false;
    };
    let provenance_ok = header
        .provenance
        .as_ref()
        .and_then(Value::as_object)
        .is_some_and(|p| {
            p.get("source_model").and_then(Value::as_str) == Some(release.repo)
                && p.get("source_revision").and_then(Value::as_str) == Some(release.revision)
                && p.get("weight_quant").and_then(Value::as_str) == Some(profile.name())
                && p.get("sampling") == Some(&flint_sampling())
        });
    arch.sliding_window == Some(FLINT_WINDOW)
        && arch.no_rope_layers.as_deref() == Some(expected_no_rope().as_slice())
        && arch.attention_sink
        && moe.router_sigmoid
        && provenance_ok
}

fn apply_repair(header: &mut CmfHeader, provenance: &Value) {
    header.arch.sliding_window = Some(FLINT_WINDOW);
    header.arch.no_rope_layers = Some(expected_no_rope());
    header.arch.attention_sink = true;
    // Flint ranks and mixes with sigmoid router scores, then renormalizes
    // the selected top-6.  Treating it as softmax changes both selection and
    // output even when every tensor byte is correct.
    header
        .arch
        .moe
        .as_mut()
        .expect("validate_flint_header checked MoE")
        .router_sigmoid = true;
    header.provenance = Some(provenance.clone());
}

fn make_plan(model: &CmfModel) -> anyhow::Result<RepairPlan> {
    let profile = inspect_quant_profile(model)?;
    let release = release_of(&model.header)?;
    Ok(RepairPlan {
        profile,
        release,
        provenance: repaired_provenance(model.header.provenance.as_ref(), profile, release)?,
        already_current: has_current_metadata(&model.header, profile),
    })
}

/// A header append only changes the file passed to `repair-flint`.  A sharded
/// export has sibling headers which would retain stale semantics, so require
/// the exact standalone distribution instead of producing a split-brain set.
fn require_standalone_repair(model: &CmfModel) -> anyhow::Result<()> {
    ensure!(
        model.header.shard.is_none(),
        "repair-flint accepts a standalone CMF only; '{}' has shard metadata",
        model.path.display()
    );
    ensure!(
        model.tensors.iter().all(|entry| entry.shard == 0),
        "repair-flint accepts a standalone CMF only; '{}' has external shard-backed tensor entries",
        model.path.display()
    );
    Ok(())
}

/// Return a fresh header with the released Flint execution semantics and
/// provenance for `profile`.  Rewriters use this rather than assuming an
/// input produced after `repair-flint`; source payloads can remain legacy
/// while the newly emitted artifact is self-describing.
pub(crate) fn repaired_flint_header(
    source: &CmfHeader,
    profile: QuantProfile,
) -> anyhow::Result<CmfHeader> {
    validate_flint_header(source)?;
    let release = release_of(source)?;
    let provenance = repaired_provenance(source.provenance.as_ref(), profile, release)?;
    let mut header = source.clone();
    apply_repair(&mut header, &provenance);
    Ok(header)
}

/// Validate both the released Flint catalogue and its already-correct
/// execution metadata.  Useful after a whole-file rewrite, where accepting a
/// stale header would make a byte-correct tensor payload execute incorrectly.
pub(crate) fn ensure_current_flint_metadata(model: &CmfModel) -> anyhow::Result<QuantProfile> {
    let profile = inspect_quant_profile(model)?;
    ensure!(
        has_current_metadata(&model.header, profile),
        "Flint tensor catalogue is valid but its semantic metadata is stale; run repair-flint"
    );
    Ok(profile)
}

/// Append the missing Flint semantic metadata in place.
///
/// `update_header_append` writes and fsyncs a new header at EOF before it
/// switches the envelope, so a cancelled repair leaves the previous model
/// readable.  It does not touch the tensor directory, data range, or vocab.
pub fn cmd_repair_flint(model_path: &str, dry_run: bool) -> anyhow::Result<()> {
    let path = Path::new(model_path);
    let model = CmfModel::open(path).with_context(|| format!("open {}", path.display()))?;
    require_standalone_repair(&model)?;
    let dir_hash = model.dir_hash();
    let plan = make_plan(&model)?;
    if plan.already_current {
        println!(
            "{}: Flint metadata is already current ({}, {}) — no changes",
            path.display(),
            plan.release.repo,
            plan.profile.name()
        );
        return Ok(());
    }
    println!(
        "{}: verified Recursive Flint catalogue ({}); profile {}; restoring window={}, 14 no-RoPE layers, 49 learned sinks, and sigmoid top-6 routing",
        path.display(),
        plan.release.repo,
        plan.profile.name(),
        FLINT_WINDOW
    );
    if dry_run {
        println!("dry run: header was not changed");
        return Ok(());
    }
    drop(model);
    let provenance = plan.provenance;
    let report =
        CmfModel::update_header_append(path, move |header| apply_repair(header, &provenance))
            .with_context(|| format!("append repaired Flint header to {}", path.display()))?;
    ensure!(
        report.tensors_added == 0 && report.data_len_before == report.data_len_after,
        "header repair unexpectedly changed tensor data"
    );
    let repaired = CmfModel::open(path).with_context(|| format!("re-open {}", path.display()))?;
    let verified = make_plan(&repaired)?;
    ensure!(
        verified.already_current,
        "repaired Flint header did not persist"
    );
    ensure!(
        repaired.dir_hash() == dir_hash,
        "header repair changed the tensor directory hash"
    );
    println!(
        "repaired {}: appended {} header bytes; tensor directory and payload bytes unchanged",
        path.display(),
        report.new_len - report.old_len
    );
    let sig = format!("{}.sig", path.display());
    if Path::new(&sig).exists() {
        eprintln!(
            "warning: {sig} signs the old complete file; re-sign it after this header update"
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use cortiq_core::{CmfHeader, ModelArch, MoeConfig, NormStyle, QuantType};

    fn old_header() -> CmfHeader {
        CmfHeader {
            format: "cmf".into(),
            version: 2,
            arch: ModelArch {
                arch_name: "flint".into(),
                hidden_size: FLINT_HIDDEN,
                intermediate_size: 6_144,
                num_layers: FLINT_LAYERS,
                num_attention_heads: FLINT_Q_HEADS,
                num_kv_heads: FLINT_KV_HEADS,
                head_dim: FLINT_HEAD_DIM,
                vocab_size: FLINT_VOCAB,
                layer_types: expected_layer_types(),
                rms_norm_eps: 1e-6,
                norm_style: NormStyle::Qwen,
                rope_theta: 10_000.0,
                tie_word_embeddings: false,
                partial_rotary_factor: 1.0,
                yarn: None,
                attention_heads_per_layer: None,
                kv_heads_per_layer: None,
                v_head_dim: None,
                hidden_act: "silu".into(),
                embed_multiplier: 1.0,
                query_pre_attn_scalar: None,
                sliding_window: None,
                sliding_window_pattern: None,
                rope_local_base_freq: None,
                local_partial_rotary_factor: None,
                global_head_dim: None,
                num_global_kv_heads: None,
                global_partial_rotary_factor: None,
                final_logit_softcapping: None,
                attn_logit_softcapping: None,
                mla: None,
                no_rope_layers: None,
                attention_sink: false,
                activation_situ_beta: None,
                activation_situ_linear_beta: None,
                ffn_clamp: None,
                attn_v_norm: false,
                qk_norm_after_rope: false,
                mtp: None,
                moe: Some(MoeConfig {
                    num_experts: FLINT_EXPERTS,
                    top_k: FLINT_TOP_K,
                    moe_intermediate_size: FLINT_EXPERT_WIDTH,
                    norm_topk_prob: true,
                    shared_expert_intermediate_size: Some(FLINT_SHARED_WIDTH),
                    router_sigmoid: false,
                    routed_scaling_factor: None,
                    router_resonance: false,
                }),
                qwen4_exp: None,
                glm5_next: None,
                block_diffusion: None,
                dory: None,
                deepseek_v41: None,
                linear_core: None,
                anchor_core: None,
                head_clusters: None,
                max_position_embeddings: 262_144,
                linear_conv_kernel_dim: None,
                linear_num_key_heads: None,
                linear_num_value_heads: None,
                linear_key_head_dim: None,
                linear_value_head_dim: None,
                num_loops: 1,
                kda_gate_lower_bound: None,
                g3n: None,
                rope_freq_factors: None,
                logit_multiplier: None,
                loop_final_norm: false,
                prism_hadamard: None,
            },
            quant_type: QuantType::Q4Block,
            provenance: Some(json!({"source_model":"/root/flint", "weight_quant":"q4tp"})),
            tokenizer_config: None,
            section_hashes: None,
            skills: Vec::new(),
            shard: None,
            calibration: None,
            routing: None,
            genome: None,
            lineage: Vec::new(),
            router: None,
            segments: Vec::new(),
        }
    }

    #[test]
    fn exact_flint_schedule_is_preserved() {
        assert_eq!(
            FLINT_NO_ROPE.iter().copied().collect::<Vec<_>>(),
            expected_no_rope()
                .iter()
                .enumerate()
                .filter_map(|(li, &no_rope)| no_rope.then_some(li))
                .collect::<Vec<_>>()
        );
        assert_eq!(
            expected_layer_types()
                .iter()
                .filter(|ty| matches!(ty, LayerType::SlidingAttention))
                .count(),
            35
        );
    }

    #[test]
    fn repair_sets_the_four_execution_semantics_and_corrects_provenance() {
        let mut header = old_header();
        validate_flint_header(&header).unwrap();
        let release = release_of(&header).unwrap();
        assert_eq!(release, FLINT_RELEASES[0], "a pre-metadata export is the first release");
        let provenance =
            repaired_provenance(header.provenance.as_ref(), QuantProfile::Q2tp, release).unwrap();
        apply_repair(&mut header, &provenance);
        assert_eq!(header.arch.sliding_window, Some(FLINT_WINDOW));
        assert_eq!(header.arch.no_rope_layers, Some(expected_no_rope()));
        assert!(header.arch.attention_sink);
        assert!(header.arch.moe.as_ref().unwrap().router_sigmoid);
        assert_eq!(
            header.provenance.as_ref().unwrap()["weight_quant"],
            json!("q2tp")
        );
        assert_eq!(
            header.provenance.as_ref().unwrap()["source_revision"],
            json!("2a247be0c0aec895ccb0ac7ca92229ec6df37288")
        );
        assert_eq!(
            header.provenance.as_ref().unwrap()["sampling"],
            flint_sampling()
        );
        assert!(has_current_metadata(&header, QuantProfile::Q2tp));
    }

    /// A header as the Flint-aware converter writes it for `release`.
    fn converted_header(provenance: Value) -> CmfHeader {
        let mut header = old_header();
        let release = FLINT_RELEASES[0];
        let repaired = repaired_provenance(None, QuantProfile::Q4tp, release).unwrap();
        apply_repair(&mut header, &repaired);
        header.provenance = Some(provenance);
        header
    }

    #[test]
    fn a_flint_1_1_file_keeps_its_release_through_repair() {
        let v11 = FLINT_RELEASES[1];
        assert_eq!(release_for_repo("recursivesi/FLINT-V1.1"), Some(v11));
        assert_eq!(release_for_repo("RecursiveSI/flint-v1.2"), None);
        let header = converted_header(json!({
            "tool": "cortiq convert",
            "source_model": "RecursiveSI/flint-v1.1",
            "source_revision": v11.revision,
            "weight_quant": "q4tp",
            "sampling": flint_sampling(),
        }));
        assert_eq!(release_of(&header).unwrap(), v11);
        assert!(
            has_current_metadata(&header, QuantProfile::Q4tp),
            "a converted Flint 1.1 file needs no repair"
        );
        // A rewrite (flint-hybrid) re-derives the header: still Flint 1.1.
        let rewritten = repaired_flint_header(&header, QuantProfile::Hybrid).unwrap();
        let p = rewritten.provenance.as_ref().unwrap();
        assert_eq!(p["source_model"], json!(v11.repo));
        assert_eq!(p["source_revision"], json!(v11.revision));
        assert_eq!(p["flint_repair"]["source_revision"], json!(v11.revision));
        assert_eq!(p["weight_quant"], json!("q2tp-q4tp-layer-hybrid"));
    }

    #[test]
    fn a_revision_alone_names_the_release() {
        let v11 = FLINT_RELEASES[1];
        let header = converted_header(json!({
            "source_model": "/content/flint-v1.1",
            "source_revision": v11.revision,
        }));
        assert_eq!(release_of(&header).unwrap(), v11);
    }

    #[test]
    fn an_unattributed_or_mismatched_flint_file_is_refused() {
        // Written by a Flint-aware converter from a local directory: the
        // release cannot be told, so it must not be stamped as the first one.
        let local = converted_header(json!({"source_model": "/content/flint", "weight_quant": "q4tp"}));
        let err = release_of(&local).unwrap_err().to_string();
        assert!(err.contains("cannot tell which Flint release"), "{err}");
        assert!(!has_current_metadata(&local, QuantProfile::Q4tp));
        assert!(repaired_flint_header(&local, QuantProfile::Q4tp).is_err());

        let crossed = converted_header(json!({
            "source_model": "RecursiveSI/flint-v1.1",
            "source_revision": FLINT_RELEASES[0].revision,
        }));
        let err = release_of(&crossed).unwrap_err().to_string();
        assert!(err.contains("not the reviewed revision"), "{err}");

        let unknown = converted_header(json!({"source_revision": "0".repeat(40)}));
        let err = release_of(&unknown).unwrap_err().to_string();
        assert!(err.contains("is not a reviewed release"), "{err}");
    }
}