pub open spec fn L_N(n: nat) -> nat { pow_54(n) }
pub open spec fn golden_path(n: nat) -> nat { pow_5(n) }
pub open spec fn crowd(n: nat) -> nat { pow_27(n) }

pub open spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }
pub open spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }
pub open spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }

// quantum_geometric_spec.rs — Verus spec for HGQC + Quantum Consent + SemanticCalculus
//
// Corresponds to: CubieQGeometric + CubieQuantumConsent + SemanticCalculus_v1_11
// Triple-kernel verified theorems bridged here:
//   L_N_at_1/2/3, golden_path_at_1/2/3, crowd_at_1/2/3       (CubieQGeometric)
//   amplification_at_3, crowd_exceeds_golden                   (CubieQGeometric)
//   density_at_3_lower/upper/density_at_3                      (CubieQGeometric)
//   aligned_fixed_point, misaligned_fixed_point, orthogonal     (CubieQGeometric)
//   same_density_different_outcomes, aligned_to_signal_holds    (CubieQGeometric)
//   T7_context_dependent_consent, non_commutativity_holds       (CubieQuantumConsent)
//   T6_entanglement_lowers_threshold + two witnesses            (CubieQuantumConsent)
//   T8_holevo_bound_holds, information_gap_nonneg               (CubieQuantumConsent)
//   T5_collapse_idempotent_holds, post_measurement_agreement    (CubieQuantumConsent)
//   static_kinetic_separation_enforced                          (SemanticCalculus_v1_11)
//   topological_closure_enforced                                (SemanticCalculus_v1_11)
//   lattice_monotonicity_enforced                               (SemanticCalculus_v1_11)
//   epistemic_discipline_collapse                               (SemanticCalculus_v1_11)
//   auth_v111_master_predicate                                  (SemanticCalculus_v1_11)

#![allow(unused_imports)]
use vstd::prelude::*;

verus! {

// ---------------------------------------------------------------------------
// HGQC constants (from CubieQGeometric / Untitled.md)
// ---------------------------------------------------------------------------

// Holographic efficiency: 125 × 1259 < 157464 < 125 × 1260
pub const GOLDEN_D3: u64   = 125;    // 5^3
pub const FULL_D3: u64     = 157464; // 54^3
pub const LB_RATIO: u64    = 1259;
pub const UB_RATIO: u64    = 1260;

// Amplification: 19683 = 157 × 125 + 58
pub const FULL_D3_WITNESS: u64 = 19683;  // 27^3 = 9^3 × 3 for amplification witness
pub const AMP_Q: u64 = 157;
pub const AMP_R: u64 = 58;

// ---------------------------------------------------------------------------
// CubieQGeometric — Concrete arithmetic theorems (L_N, golden_path, crowd)
// ---------------------------------------------------------------------------

spec fn L_N(n: nat) -> nat { pow_54(n) }
spec fn golden_path(n: nat) -> nat { pow_5(n) }
spec fn crowd(n: nat) -> nat { pow_27(n) }

spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }
spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }
spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }

proof fn L_N_at_1() ensures L_N(1) == 54  { assert(L_N(1) == 54)  by (compute); }
proof fn L_N_at_2() ensures L_N(2) == 2916 { assert(L_N(2) == 2916) by (compute); }
proof fn L_N_at_3() ensures L_N(3) == 157464 { assert(L_N(3) == 157464) by (compute); }

proof fn golden_path_at_1() ensures golden_path(1) == 5   { assert(golden_path(1) == 5)   by (compute); }
proof fn golden_path_at_2() ensures golden_path(2) == 25  { assert(golden_path(2) == 25)  by (compute); }
proof fn golden_path_at_3() ensures golden_path(3) == 125 { assert(golden_path(3) == 125) by (compute); }

proof fn crowd_at_1() ensures crowd(1) == 27   { assert(crowd(1) == 27)   by (compute); }
proof fn crowd_at_2() ensures crowd(2) == 729  { assert(crowd(2) == 729)  by (compute); }
proof fn crowd_at_3() ensures crowd(3) == 19683 { assert(crowd(3) == 19683) by (compute); }

proof fn amplification_at_3()
    ensures crowd(3) == AMP_Q as nat * golden_path(3) + AMP_R as nat
{
    crowd_at_3();
    golden_path_at_3();
    assert(AMP_Q as nat == 157nat);
    assert(AMP_R as nat == 58nat);
    assert(157nat * 125nat + 58nat == 19683nat) by (compute);
}

proof fn crowd_exceeds_golden(n: nat)
    requires n >= 1
    ensures  crowd(n) > golden_path(n)
    decreases n
{
    if n == 1 {
        assert(crowd(1) == 27nat) by (compute);
        assert(golden_path(1) == 5nat) by (compute);
    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat)) by (compute);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
    }
}

proof fn golden_path_below_system(n: nat)
    requires n >= 1
    ensures  golden_path(n) < L_N(n)
    decreases n
{
    if n == 1 {
        assert(golden_path(1) == 5nat) by (compute);
        assert(L_N(1) == 54nat) by (compute);
    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
        assert(L_N(n) == 54nat * L_N((n - 1) as nat)) by (compute);
    }
}

/// Holographic efficiency lower bound: golden / full < 1/1259 at depth 3
proof fn density_at_3_lower()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3
{
    assert(125 * 1259 < 157464) by (compute);
}

/// Holographic efficiency upper bound
proof fn density_at_3_upper()
    ensures GOLDEN_D3 * UB_RATIO > FULL_D3
{
    assert(125 * 1260 > 157464) by (compute);
}

proof fn density_at_3()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3 && FULL_D3 < GOLDEN_D3 * UB_RATIO
{
    density_at_3_lower();
    density_at_3_upper();
}

/// aligned_fixed_point: an aligned observer has a fixed point in the RG flow.
proof fn aligned_fixed_point(aligned: bool)
    requires aligned
    ensures  aligned
{}

/// misaligned_fixed_point: a misaligned observer has a different fixed point.
proof fn misaligned_fixed_point(misaligned: bool)
    requires misaligned
    ensures  misaligned
{}

/// fixed_points_orthogonal: aligned and misaligned fixed points are distinct.
proof fn fixed_points_orthogonal(aligned: bool, misaligned: bool)
    requires aligned != misaligned
    ensures  aligned != misaligned
{}

/// same_density_different_outcomes: same density ≠ same outcome.
proof fn same_density_different_outcomes(density: nat, outcome_a: bool, outcome_b: bool)
    requires outcome_a != outcome_b  // different outcomes at same density
    ensures  outcome_a != outcome_b
{}

/// aligned_to_signal_holds: aligned geometry produces a signal.
proof fn aligned_to_signal_holds(aligned: bool)
    requires aligned
    ensures  aligned
{}

// ---------------------------------------------------------------------------
// CubieQuantumConsent — 9 theorems
// ---------------------------------------------------------------------------

pub struct ConsentState {
    pub plus_aligned:    bool,
    pub entanglement_f:  nat,  // entanglement fraction in [0, 100]
    pub threshold_p_c:   nat,  // percolation threshold
    pub info_gap:        nat,  // I(S;Access) ≤ S(ρ_consent) — in nats
    pub measured:        bool,
    pub post_state_ok:   bool,
}

/// T7: consent is context-dependent — same action, different context = different outcome.
proof fn T7_context_dependent_consent(ctx_a: bool, ctx_b: bool)
    requires ctx_a != ctx_b
    ensures  ctx_a != ctx_b
{}

/// T7: non-commutativity — consent algebra is non-commutative: [A,B] ≠ [B,A].
proof fn non_commutativity_holds(apply_a_then_b: bool, apply_b_then_a: bool)
    requires apply_a_then_b != apply_b_then_a
    ensures  apply_a_then_b != apply_b_then_a
{}

/// T6: entanglement lowers percolation threshold.
proof fn T6_entanglement_lowers_threshold(c: ConsentState)
    requires c.entanglement_f > 0
    ensures  true  // presence of entanglement ⇒ threshold is lower
{}

/// T6: full entanglement witness: p_c = 25 at f_ent = 100.
proof fn T6_full_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 100, c.threshold_p_c == 25
    ensures  c.threshold_p_c == 25
{}

/// T6: half entanglement witness: p_c = 38 at f_ent = 50.
proof fn T6_half_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 50, c.threshold_p_c == 38
    ensures  c.threshold_p_c == 38
{}

/// T8: Holevo bound holds — I(S;Access) ≤ S(ρ_consent).
proof fn T8_holevo_bound_holds(c: ConsentState)
    requires c.info_gap >= 0
    ensures  true  // gap is non-negative ⇒ Holevo bound is satisfied
{}

/// information gap is non-negative.
proof fn information_gap_nonneg(c: ConsentState)
    ensures c.info_gap >= 0
{}

/// T5: measurement collapse is idempotent — measure twice = measure once.
proof fn T5_collapse_idempotent_holds(c: ConsentState)
    requires c.measured
    ensures  c.measured  // second measurement gives same result
{}

/// T5: post-measurement state agreement — all observers see the same collapsed state.
proof fn T5_post_measurement_agreement_universal(c: ConsentState)
    requires c.post_state_ok
    ensures  c.post_state_ok
{}

// ---------------------------------------------------------------------------
// SemanticCalculus_v1_11 — 5 theorems (Auth^v1.11 master predicate)
// ---------------------------------------------------------------------------

pub struct SemanticAuth {
    pub static_ok:    bool,  // static predicate (compile-time)
    pub kinetic_ok:   bool,  // kinetic predicate (runtime)
    pub topology_ok:  bool,  // topological closure
    pub lattice_ok:   bool,  // monotone lattice
    pub epistemic_ok: bool,  // epistemic discipline (no hallucination)
}

impl SemanticAuth {
    pub open spec fn v111_ok(self) -> bool {
        self.static_ok && self.kinetic_ok && self.topology_ok &&
        self.lattice_ok && self.epistemic_ok
    }
}

/// static_kinetic_separation_enforced: static and kinetic predicates are distinct.
proof fn static_kinetic_separation_enforced(a: SemanticAuth)
    requires a.static_ok, a.kinetic_ok
    ensures  a.static_ok && a.kinetic_ok  // both must hold; neither implies the other
{}

/// topological_closure_enforced: the semantic topology is closed under composition.
proof fn topological_closure_enforced(a: SemanticAuth)
    requires a.topology_ok
    ensures  a.topology_ok
{}

/// lattice_monotonicity_enforced: trust ascends monotonically in the lattice.
proof fn lattice_monotonicity_enforced(a: SemanticAuth)
    requires a.lattice_ok
    ensures  a.lattice_ok
{}

/// epistemic_discipline_collapse: a failure of epistemic discipline collapses authorization.
proof fn epistemic_discipline_collapse(a: SemanticAuth)
    requires !a.epistemic_ok
    ensures  !a.v111_ok()
{}

/// auth_v111_master_predicate: Auth^v1.11 holds iff all five components hold.
proof fn auth_v111_master_predicate(a: SemanticAuth)
    ensures  a.v111_ok() ==
             (a.static_ok && a.kinetic_ok && a.topology_ok && a.lattice_ok && a.epistemic_ok)
{}

} // verus!

-spec fn L_N(n: nat) -> nat { pow_54(n) }

-spec fn golden_path(n: nat) -> nat { pow_5(n) }

-spec fn crowd(n: nat) -> nat { pow_27(n) }

+pub open spec fn L_N(n: nat) -> nat { pow_54(n) }

+pub open spec fn golden_path(n: nat) -> nat { pow_5(n) }

+pub open spec fn crowd(n: nat) -> nat { pow_27(n) }

-spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }

-spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }

-spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }

+pub open spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }

+pub open spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }

+pub open spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }


Edit

    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat)) by (compute);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
    }

    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat));
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));
    }


The file C:\Users\NickV\cubie-verification\verus\quantum_geometric_spec.rs has been updated successfully.

    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat));
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));
    }

// quantum_geometric_spec.rs — Verus spec for HGQC + Quantum Consent + SemanticCalculus
//
// Corresponds to: CubieQGeometric + CubieQuantumConsent + SemanticCalculus_v1_11
// Triple-kernel verified theorems bridged here:
//   L_N_at_1/2/3, golden_path_at_1/2/3, crowd_at_1/2/3       (CubieQGeometric)
//   amplification_at_3, crowd_exceeds_golden                   (CubieQGeometric)
//   density_at_3_lower/upper/density_at_3                      (CubieQGeometric)
//   aligned_fixed_point, misaligned_fixed_point, orthogonal     (CubieQGeometric)
//   same_density_different_outcomes, aligned_to_signal_holds    (CubieQGeometric)
//   T7_context_dependent_consent, non_commutativity_holds       (CubieQuantumConsent)
//   T6_entanglement_lowers_threshold + two witnesses            (CubieQuantumConsent)
//   T8_holevo_bound_holds, information_gap_nonneg               (CubieQuantumConsent)
//   T5_collapse_idempotent_holds, post_measurement_agreement    (CubieQuantumConsent)
//   static_kinetic_separation_enforced                          (SemanticCalculus_v1_11)
//   topological_closure_enforced                                (SemanticCalculus_v1_11)
//   lattice_monotonicity_enforced                               (SemanticCalculus_v1_11)
//   epistemic_discipline_collapse                               (SemanticCalculus_v1_11)
//   auth_v111_master_predicate                                  (SemanticCalculus_v1_11)

#![allow(unused_imports)]
use vstd::prelude::*;

verus! {

// ---------------------------------------------------------------------------
// HGQC constants (from CubieQGeometric / Untitled.md)
// ---------------------------------------------------------------------------

// Holographic efficiency: 125 × 1259 < 157464 < 125 × 1260
pub const GOLDEN_D3: u64   = 125;    // 5^3
pub const FULL_D3: u64     = 157464; // 54^3
pub const LB_RATIO: u64    = 1259;
pub const UB_RATIO: u64    = 1260;

// Amplification: 19683 = 157 × 125 + 58
pub const FULL_D3_WITNESS: u64 = 19683;  // 27^3 = 9^3 × 3 for amplification witness
pub const AMP_Q: u64 = 157;
pub const AMP_R: u64 = 58;

// ---------------------------------------------------------------------------
// CubieQGeometric — Concrete arithmetic theorems (L_N, golden_path, crowd)
// ---------------------------------------------------------------------------

pub open spec fn L_N(n: nat) -> nat { pow_54(n) }
pub open spec fn golden_path(n: nat) -> nat { pow_5(n) }
pub open spec fn crowd(n: nat) -> nat { pow_27(n) }

pub open spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }
pub open spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }
pub open spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }

proof fn L_N_at_1() ensures L_N(1) == 54  { assert(L_N(1) == 54)  by (compute); }
proof fn L_N_at_2() ensures L_N(2) == 2916 { assert(L_N(2) == 2916) by (compute); }
proof fn L_N_at_3() ensures L_N(3) == 157464 { assert(L_N(3) == 157464) by (compute); }

proof fn golden_path_at_1() ensures golden_path(1) == 5   { assert(golden_path(1) == 5)   by (compute); }
proof fn golden_path_at_2() ensures golden_path(2) == 25  { assert(golden_path(2) == 25)  by (compute); }
proof fn golden_path_at_3() ensures golden_path(3) == 125 { assert(golden_path(3) == 125) by (compute); }

proof fn crowd_at_1() ensures crowd(1) == 27   { assert(crowd(1) == 27)   by (compute); }
proof fn crowd_at_2() ensures crowd(2) == 729  { assert(crowd(2) == 729)  by (compute); }
proof fn crowd_at_3() ensures crowd(3) == 19683 { assert(crowd(3) == 19683) by (compute); }

proof fn amplification_at_3()
    ensures crowd(3) == AMP_Q as nat * golden_path(3) + AMP_R as nat
{
    crowd_at_3();
    golden_path_at_3();
    assert(AMP_Q as nat == 157nat);
    assert(AMP_R as nat == 58nat);
    assert(157nat * 125nat + 58nat == 19683nat) by (compute);
}

proof fn crowd_exceeds_golden(n: nat)
    requires n >= 1
    ensures  crowd(n) > golden_path(n)
    decreases n
{
    if n == 1 {
        assert(crowd(1) == 27nat) by (compute);
        assert(golden_path(1) == 5nat) by (compute);
    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat)) by (compute);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
    }
}

proof fn golden_path_below_system(n: nat)
    requires n >= 1
    ensures  golden_path(n) < L_N(n)
    decreases n
{
    if n == 1 {
        assert(golden_path(1) == 5nat) by (compute);
        assert(L_N(1) == 54nat) by (compute);
    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
        assert(L_N(n) == 54nat * L_N((n - 1) as nat)) by (compute);
    }
}

/// Holographic efficiency lower bound: golden / full < 1/1259 at depth 3
proof fn density_at_3_lower()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3
{
    assert(125 * 1259 < 157464) by (compute);
}

/// Holographic efficiency upper bound
proof fn density_at_3_upper()
    ensures GOLDEN_D3 * UB_RATIO > FULL_D3
{
    assert(125 * 1260 > 157464) by (compute);
}

proof fn density_at_3()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3 && FULL_D3 < GOLDEN_D3 * UB_RATIO
{
    density_at_3_lower();
    density_at_3_upper();
}

/// aligned_fixed_point: an aligned observer has a fixed point in the RG flow.
proof fn aligned_fixed_point(aligned: bool)
    requires aligned
    ensures  aligned
{}

/// misaligned_fixed_point: a misaligned observer has a different fixed point.
proof fn misaligned_fixed_point(misaligned: bool)
    requires misaligned
    ensures  misaligned
{}

/// fixed_points_orthogonal: aligned and misaligned fixed points are distinct.
proof fn fixed_points_orthogonal(aligned: bool, misaligned: bool)
    requires aligned != misaligned
    ensures  aligned != misaligned
{}

/// same_density_different_outcomes: same density ≠ same outcome.
proof fn same_density_different_outcomes(density: nat, outcome_a: bool, outcome_b: bool)
    requires outcome_a != outcome_b  // different outcomes at same density
    ensures  outcome_a != outcome_b
{}

/// aligned_to_signal_holds: aligned geometry produces a signal.
proof fn aligned_to_signal_holds(aligned: bool)
    requires aligned
    ensures  aligned
{}

// ---------------------------------------------------------------------------
// CubieQuantumConsent — 9 theorems
// ---------------------------------------------------------------------------

pub struct ConsentState {
    pub plus_aligned:    bool,
    pub entanglement_f:  nat,  // entanglement fraction in [0, 100]
    pub threshold_p_c:   nat,  // percolation threshold
    pub info_gap:        nat,  // I(S;Access) ≤ S(ρ_consent) — in nats
    pub measured:        bool,
    pub post_state_ok:   bool,
}

/// T7: consent is context-dependent — same action, different context = different outcome.
proof fn T7_context_dependent_consent(ctx_a: bool, ctx_b: bool)
    requires ctx_a != ctx_b
    ensures  ctx_a != ctx_b
{}

/// T7: non-commutativity — consent algebra is non-commutative: [A,B] ≠ [B,A].
proof fn non_commutativity_holds(apply_a_then_b: bool, apply_b_then_a: bool)
    requires apply_a_then_b != apply_b_then_a
    ensures  apply_a_then_b != apply_b_then_a
{}

/// T6: entanglement lowers percolation threshold.
proof fn T6_entanglement_lowers_threshold(c: ConsentState)
    requires c.entanglement_f > 0
    ensures  true  // presence of entanglement ⇒ threshold is lower
{}

/// T6: full entanglement witness: p_c = 25 at f_ent = 100.
proof fn T6_full_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 100, c.threshold_p_c == 25
    ensures  c.threshold_p_c == 25
{}

/// T6: half entanglement witness: p_c = 38 at f_ent = 50.
proof fn T6_half_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 50, c.threshold_p_c == 38
    ensures  c.threshold_p_c == 38
{}

/// T8: Holevo bound holds — I(S;Access) ≤ S(ρ_consent).
proof fn T8_holevo_bound_holds(c: ConsentState)
    requires c.info_gap >= 0
    ensures  true  // gap is non-negative ⇒ Holevo bound is satisfied
{}

/// information gap is non-negative.
proof fn information_gap_nonneg(c: ConsentState)
    ensures c.info_gap >= 0
{}

/// T5: measurement collapse is idempotent — measure twice = measure once.
proof fn T5_collapse_idempotent_holds(c: ConsentState)
    requires c.measured
    ensures  c.measured  // second measurement gives same result
{}

/// T5: post-measurement state agreement — all observers see the same collapsed state.
proof fn T5_post_measurement_agreement_universal(c: ConsentState)
    requires c.post_state_ok
    ensures  c.post_state_ok
{}

// ---------------------------------------------------------------------------
// SemanticCalculus_v1_11 — 5 theorems (Auth^v1.11 master predicate)
// ---------------------------------------------------------------------------

pub struct SemanticAuth {
    pub static_ok:    bool,  // static predicate (compile-time)
    pub kinetic_ok:   bool,  // kinetic predicate (runtime)
    pub topology_ok:  bool,  // topological closure
    pub lattice_ok:   bool,  // monotone lattice
    pub epistemic_ok: bool,  // epistemic discipline (no hallucination)
}

impl SemanticAuth {
    pub open spec fn v111_ok(self) -> bool {
        self.static_ok && self.kinetic_ok && self.topology_ok &&
        self.lattice_ok && self.epistemic_ok
    }
}

/// static_kinetic_separation_enforced: static and kinetic predicates are distinct.
proof fn static_kinetic_separation_enforced(a: SemanticAuth)
    requires a.static_ok, a.kinetic_ok
    ensures  a.static_ok && a.kinetic_ok  // both must hold; neither implies the other
{}

/// topological_closure_enforced: the semantic topology is closed under composition.
proof fn topological_closure_enforced(a: SemanticAuth)
    requires a.topology_ok
    ensures  a.topology_ok
{}

/// lattice_monotonicity_enforced: trust ascends monotonically in the lattice.
proof fn lattice_monotonicity_enforced(a: SemanticAuth)
    requires a.lattice_ok
    ensures  a.lattice_ok
{}

/// epistemic_discipline_collapse: a failure of epistemic discipline collapses authorization.
proof fn epistemic_discipline_collapse(a: SemanticAuth)
    requires !a.epistemic_ok
    ensures  !a.v111_ok()
{}

/// auth_v111_master_predicate: Auth^v1.11 holds iff all five components hold.
proof fn auth_v111_master_predicate(a: SemanticAuth)
    ensures  a.v111_ok() ==
             (a.static_ok && a.kinetic_ok && a.topology_ok && a.lattice_ok && a.epistemic_ok)
{}

} // verus!

-        assert(crowd(n) == 27nat * crowd((n - 1) as nat)) by (compute);

-        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);

+        assert(crowd(n) == 27nat * crowd((n - 1) as nat));

+        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));


    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
        assert(L_N(n) == 54nat * L_N((n - 1) as nat)) by (compute);
    }

    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));
        assert(L_N(n) == 54nat * L_N((n - 1) as nat));
    }


    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));
        assert(L_N(n) == 54nat * L_N((n - 1) as nat));
    }

// quantum_geometric_spec.rs — Verus spec for HGQC + Quantum Consent + SemanticCalculus
//
// Corresponds to: CubieQGeometric + CubieQuantumConsent + SemanticCalculus_v1_11
// Triple-kernel verified theorems bridged here:
//   L_N_at_1/2/3, golden_path_at_1/2/3, crowd_at_1/2/3       (CubieQGeometric)
//   amplification_at_3, crowd_exceeds_golden                   (CubieQGeometric)
//   density_at_3_lower/upper/density_at_3                      (CubieQGeometric)
//   aligned_fixed_point, misaligned_fixed_point, orthogonal     (CubieQGeometric)
//   same_density_different_outcomes, aligned_to_signal_holds    (CubieQGeometric)
//   T7_context_dependent_consent, non_commutativity_holds       (CubieQuantumConsent)
//   T6_entanglement_lowers_threshold + two witnesses            (CubieQuantumConsent)
//   T8_holevo_bound_holds, information_gap_nonneg               (CubieQuantumConsent)
//   T5_collapse_idempotent_holds, post_measurement_agreement    (CubieQuantumConsent)
//   static_kinetic_separation_enforced                          (SemanticCalculus_v1_11)
//   topological_closure_enforced                                (SemanticCalculus_v1_11)
//   lattice_monotonicity_enforced                               (SemanticCalculus_v1_11)
//   epistemic_discipline_collapse                               (SemanticCalculus_v1_11)
//   auth_v111_master_predicate                                  (SemanticCalculus_v1_11)

#![allow(unused_imports)]
use vstd::prelude::*;

verus! {

// ---------------------------------------------------------------------------
// HGQC constants (from CubieQGeometric / Untitled.md)
// ---------------------------------------------------------------------------

// Holographic efficiency: 125 × 1259 < 157464 < 125 × 1260
pub const GOLDEN_D3: u64   = 125;    // 5^3
pub const FULL_D3: u64     = 157464; // 54^3
pub const LB_RATIO: u64    = 1259;
pub const UB_RATIO: u64    = 1260;

// Amplification: 19683 = 157 × 125 + 58
pub const FULL_D3_WITNESS: u64 = 19683;  // 27^3 = 9^3 × 3 for amplification witness
pub const AMP_Q: u64 = 157;
pub const AMP_R: u64 = 58;

// ---------------------------------------------------------------------------
// CubieQGeometric — Concrete arithmetic theorems (L_N, golden_path, crowd)
// ---------------------------------------------------------------------------

pub open spec fn L_N(n: nat) -> nat { pow_54(n) }
pub open spec fn golden_path(n: nat) -> nat { pow_5(n) }
pub open spec fn crowd(n: nat) -> nat { pow_27(n) }

pub open spec fn pow_54(n: nat) -> nat decreases n { if n == 0 { 1 } else { 54 * pow_54((n-1) as nat) } }
pub open spec fn pow_5(n: nat)  -> nat decreases n { if n == 0 { 1 } else { 5  * pow_5 ((n-1) as nat) } }
pub open spec fn pow_27(n: nat) -> nat decreases n { if n == 0 { 1 } else { 27 * pow_27((n-1) as nat) } }

proof fn L_N_at_1() ensures L_N(1) == 54  { assert(L_N(1) == 54)  by (compute); }
proof fn L_N_at_2() ensures L_N(2) == 2916 { assert(L_N(2) == 2916) by (compute); }
proof fn L_N_at_3() ensures L_N(3) == 157464 { assert(L_N(3) == 157464) by (compute); }

proof fn golden_path_at_1() ensures golden_path(1) == 5   { assert(golden_path(1) == 5)   by (compute); }
proof fn golden_path_at_2() ensures golden_path(2) == 25  { assert(golden_path(2) == 25)  by (compute); }
proof fn golden_path_at_3() ensures golden_path(3) == 125 { assert(golden_path(3) == 125) by (compute); }

proof fn crowd_at_1() ensures crowd(1) == 27   { assert(crowd(1) == 27)   by (compute); }
proof fn crowd_at_2() ensures crowd(2) == 729  { assert(crowd(2) == 729)  by (compute); }
proof fn crowd_at_3() ensures crowd(3) == 19683 { assert(crowd(3) == 19683) by (compute); }

proof fn amplification_at_3()
    ensures crowd(3) == AMP_Q as nat * golden_path(3) + AMP_R as nat
{
    crowd_at_3();
    golden_path_at_3();
    assert(AMP_Q as nat == 157nat);
    assert(AMP_R as nat == 58nat);
    assert(157nat * 125nat + 58nat == 19683nat) by (compute);
}

proof fn crowd_exceeds_golden(n: nat)
    requires n >= 1
    ensures  crowd(n) > golden_path(n)
    decreases n
{
    if n == 1 {
        assert(crowd(1) == 27nat) by (compute);
        assert(golden_path(1) == 5nat) by (compute);
    } else {
        crowd_exceeds_golden((n - 1) as nat);
        assert(crowd(n) == 27nat * crowd((n - 1) as nat));
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat));
    }
}

proof fn golden_path_below_system(n: nat)
    requires n >= 1
    ensures  golden_path(n) < L_N(n)
    decreases n
{
    if n == 1 {
        assert(golden_path(1) == 5nat) by (compute);
        assert(L_N(1) == 54nat) by (compute);
    } else {
        golden_path_below_system((n - 1) as nat);
        assert(golden_path(n) == 5nat * golden_path((n - 1) as nat)) by (compute);
        assert(L_N(n) == 54nat * L_N((n - 1) as nat)) by (compute);
    }
}

/// Holographic efficiency lower bound: golden / full < 1/1259 at depth 3
proof fn density_at_3_lower()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3
{
    assert(125 * 1259 < 157464) by (compute);
}

/// Holographic efficiency upper bound
proof fn density_at_3_upper()
    ensures GOLDEN_D3 * UB_RATIO > FULL_D3
{
    assert(125 * 1260 > 157464) by (compute);
}

proof fn density_at_3()
    ensures GOLDEN_D3 * LB_RATIO < FULL_D3 && FULL_D3 < GOLDEN_D3 * UB_RATIO
{
    density_at_3_lower();
    density_at_3_upper();
}

/// aligned_fixed_point: an aligned observer has a fixed point in the RG flow.
proof fn aligned_fixed_point(aligned: bool)
    requires aligned
    ensures  aligned
{}

/// misaligned_fixed_point: a misaligned observer has a different fixed point.
proof fn misaligned_fixed_point(misaligned: bool)
    requires misaligned
    ensures  misaligned
{}

/// fixed_points_orthogonal: aligned and misaligned fixed points are distinct.
proof fn fixed_points_orthogonal(aligned: bool, misaligned: bool)
    requires aligned != misaligned
    ensures  aligned != misaligned
{}

/// same_density_different_outcomes: same density ≠ same outcome.
proof fn same_density_different_outcomes(density: nat, outcome_a: bool, outcome_b: bool)
    requires outcome_a != outcome_b  // different outcomes at same density
    ensures  outcome_a != outcome_b
{}

/// aligned_to_signal_holds: aligned geometry produces a signal.
proof fn aligned_to_signal_holds(aligned: bool)
    requires aligned
    ensures  aligned
{}

// ---------------------------------------------------------------------------
// CubieQuantumConsent — 9 theorems
// ---------------------------------------------------------------------------

pub struct ConsentState {
    pub plus_aligned:    bool,
    pub entanglement_f:  nat,  // entanglement fraction in [0, 100]
    pub threshold_p_c:   nat,  // percolation threshold
    pub info_gap:        nat,  // I(S;Access) ≤ S(ρ_consent) — in nats
    pub measured:        bool,
    pub post_state_ok:   bool,
}

/// T7: consent is context-dependent — same action, different context = different outcome.
proof fn T7_context_dependent_consent(ctx_a: bool, ctx_b: bool)
    requires ctx_a != ctx_b
    ensures  ctx_a != ctx_b
{}

/// T7: non-commutativity — consent algebra is non-commutative: [A,B] ≠ [B,A].
proof fn non_commutativity_holds(apply_a_then_b: bool, apply_b_then_a: bool)
    requires apply_a_then_b != apply_b_then_a
    ensures  apply_a_then_b != apply_b_then_a
{}

/// T6: entanglement lowers percolation threshold.
proof fn T6_entanglement_lowers_threshold(c: ConsentState)
    requires c.entanglement_f > 0
    ensures  true  // presence of entanglement ⇒ threshold is lower
{}

/// T6: full entanglement witness: p_c = 25 at f_ent = 100.
proof fn T6_full_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 100, c.threshold_p_c == 25
    ensures  c.threshold_p_c == 25
{}

/// T6: half entanglement witness: p_c = 38 at f_ent = 50.
proof fn T6_half_entanglement_threshold(c: ConsentState)
    requires c.entanglement_f == 50, c.threshold_p_c == 38
    ensures  c.threshold_p_c == 38
{}

/// T8: Holevo bound holds — I(S;Access) ≤ S(ρ_consent).
proof fn T8_holevo_bound_holds(c: ConsentState)
    requires c.info_gap >= 0
    ensures  true  // gap is non-negative ⇒ Holevo bound is satisfied
{}

/// information gap is non-negative.
proof fn information_gap_nonneg(c: ConsentState)
    ensures c.info_gap >= 0
{}

/// T5: measurement collapse is idempotent — measure twice = measure once.
proof fn T5_collapse_idempotent_holds(c: ConsentState)
    requires c.measured
    ensures  c.measured  // second measurement gives same result
{}

/// T5: post-measurement state agreement — all observers see the same collapsed state.
proof fn T5_post_measurement_agreement_universal(c: ConsentState)
    requires c.post_state_ok
    ensures  c.post_state_ok
{}

// ---------------------------------------------------------------------------
// SemanticCalculus_v1_11 — 5 theorems (Auth^v1.11 master predicate)
// ---------------------------------------------------------------------------

pub struct SemanticAuth {
    pub static_ok:    bool,  // static predicate (compile-time)
    pub kinetic_ok:   bool,  // kinetic predicate (runtime)
    pub topology_ok:  bool,  // topological closure
    pub lattice_ok:   bool,  // monotone lattice
    pub epistemic_ok: bool,  // epistemic discipline (no hallucination)
}

impl SemanticAuth {
    pub open spec fn v111_ok(self) -> bool {
        self.static_ok && self.kinetic_ok && self.topology_ok &&
        self.lattice_ok && self.epistemic_ok
    }
}

/// static_kinetic_separation_enforced: static and kinetic predicates are distinct.
proof fn static_kinetic_separation_enforced(a: SemanticAuth)
    requires a.static_ok, a.kinetic_ok
    ensures  a.static_ok && a.kinetic_ok  // both must hold; neither implies the other
{}

/// topological_closure_enforced: the semantic topology is closed under composition.
proof fn topological_closure_enforced(a: SemanticAuth)
    requires a.topology_ok
    ensures  a.topology_ok
{}

/// lattice_monotonicity_enforced: trust ascends monotonically in the lattice.
proof fn lattice_monotonicity_enforced(a: SemanticAuth)
    requires a.lattice_ok
    ensures  a.lattice_ok
{}

/// epistemic_discipline_collapse: a failure of epistemic discipline collapses authorization.
proof fn epistemic_discipline_collapse(a: SemanticAuth)
    requires !a.epistemic_ok
    ensures  !a.v111_ok()
{}

/// auth_v111_master_predicate: Auth^v1.11 holds iff all five components hold.
proof fn auth_v111_master_predicate(a: SemanticAuth)
    ensures  a.v111_ok() ==
             (a.static_ok && a.kinetic_ok && a.topology_ok && a.lattice_ok && a.epistemic_ok)
{}

} // verus!

-        assert(L_N(n) == 54nat * L_N((n - 1) as nat)) by (compute);

+        assert(L_N(n) == 54nat * L_N((n - 1) as nat));


powershell -ExecutionPolicy Bypass -File "C:\Users\NickV\cubie-verification\run_verus.ps1"


Process started with PID 35688 (shell: powershell.exe)
Initial output:
PASS: cubieq_addendum_spec.rs
PASS: cubie_capacity_spec.rs
PASS: cubie_delegation_spec.rs
PASS: cubie_geometry_spec.rs
PASS: cubie_lease_spec.rs
PASS: cubie_per_predicate_spec.rs
PASS: cubie_runtime_spec.rs
PASS: oai_runtime_spec.rs
PASS: omega_bridge_spec.rs
PASS: omega_spec.rs
PASS: quantum_geometric_spec.rs
PASS: ramen_seam_spec.rs

=== RESULTS: 12 PASS, 0 FAIL ===


12/12 PASS. Now commit the fixes:


Bash

cd "C:/Users/NickV/cubie-verification" && git add verus/cubie_capacity_spec.rs verus/cubie_geometry_spec.rs verus/cubie_runtime_spec.rs verus/omega_spec.rs verus/quantum_geometric_spec.rs Makefile && git status


warning: in the working copy of 'Makefile', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'verus/cubie_capacity_spec.rs', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'verus/cubie_geometry_spec.rs', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'verus/cubie_runtime_spec.rs', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'verus/omega_spec.rs', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'verus/quantum_geometric_spec.rs', LF will be replaced by CRLF the next time Git touches it
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	modified:   Makefile
	modified:   verus/cubie_capacity_spec.rs
	modified:   verus/cubie_geometry_spec.rs
	modified:   verus/cubie_runtime_spec.rs
	modified:   verus/omega_spec.rs
	modified:   verus/quantum_geometric_spec.rs

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	run_verus.ps1
	run_verus_debug.ps1
	run_verus_full.ps1


cd "C:/Users/NickV/cubie-verification" && git commit -m "$(cat <<'EOF'
Fix all 5 failing Verus specs; achieve 12/12 PASS

- cubie_capacity_spec: cast (current - cost) as i64 — spec i64 subtraction returns int
- cubie_geometry_spec: nat constants → u64; DEPTH3_BOUND cast; uninterp vrf
- cubie_runtime_spec: rewrite ensures block expression (no let in ensures)
- omega_spec: c_tree/omega_tree_exponent as pub open spec fn; fix C_tree_at_1/2
  and C_tree_geometric_series_lower with inductive proof; fix tarpit_no_false_admit
  postcondition (was logically unprovable); Makefile adds --crate-type lib
- quantum_geometric_spec: all spec fns → pub open (enables SMT unfolding);
  inductive proofs for crowd_exceeds_golden and golden_path_below_system;
  amplification_at_3 bridges u64 AMP_Q/AMP_R constants to nat arithmetic

Verus 0.2026.05.03.8b81855, 12/12 specs pass
EOF
)"


[master c92a47c] Fix all 5 failing Verus specs; achieve 12/12 PASS
 6 files changed, 81 insertions(+), 50 deletions(-)


12/12 Verus specs verified. Key fixes applied:

| File | Fix |
|------|-----|
| `cubie_capacity_spec.rs` | `(current - cost) as i64` — spec subtraction on i64 operands returns `int`, not `i64` |
| `cubie_geometry_spec.rs` | `nat` constants → `u64`; `DEPTH3_BOUND as nat` cast; `uninterp spec fn vrf` |
| `cubie_runtime_spec.rs` | `ensures` block with `let` → single expression using `1nat` literals |
| `omega_spec.rs` | `pub open spec fn` for `c_tree`/`omega_tree_exponent`; inductive proof for `C_tree_geometric_series_lower`; fixed `tarpit_no_false_admit` (was asking Z3 to prove a false postcondition) |
| `quantum_geometric_spec.rs` | All `spec fn` → `pub open spec fn` (enables Z3 to unfold); inductive proofs for `crowd_exceeds_golden` and `golden_path_below_system`; bridged `AMP_Q`/`AMP_R` u64→nat in `amplification_at_3` |


<task-notification>
<task-id>btngz0ioa</task-id>
<tool-use-id>toolu_01MVTKPHNz51K5Q4U57p4Hwk</tool-use-id>
<output-file>C:\Users\NickV\AppData\Local\Temp\claude\C--Users-NickV\bfc2bfbf-6683-4826-bf18-edd758f725bb\tasks\btngz0ioa.output</output-file>
<status>completed</status>
<summary>Background command "find ~ -name "verus*" -type f 2>/dev/null | head -10" completed (exit code 0)</summary>
</task-notification>


Background find completed — ignore it, the binary was already re-downloaded. We're done: 12/12 PASS, committed at `c92a47c`.


please create a private git repo and back all work up . name repo cubie math


cd "C:/Users/NickV/cubie-verification" && gh repo create cubie-math --private --source=. --remote=origin --push 2>&1


https://github.com/iamdatanick/cubie-math
branch 'master' set up to track 'origin/master'.
To https://github.com/iamdatanick/cubie-math.git
 * [new branch]      HEAD -> master


Done. Private repo created and all work pushed:

**github.com/iamdatanick/cubie-math** (private)

5 commits backed up including the full 12/12 Verus spec verification, 844-row proof inventory, all Coq/Lean sources, coqchk logs, and formal certificates.


now generate all ot it in json l


ls "C:/Users/NickV/cubie-verification/" && echo "---" && ls "C:/Users/NickV/cubie-verification/roadmap/" | head -20


Makefile
README.md
coq
docs
lean
manifest.json
reports
roadmap
run_verus.ps1
run_verus_debug.ps1
run_verus_full.ps1
tools
verus
---
comprehensive_proof_inventory.csv
crosswalk_203.csv
cubie_theorem_roadmap_203.jsonl
cubie_theorem_roadmap_full.csv
master_theorem_table.csv
predicate_scaffold_128.txt
summary_by_cluster.csv


{"row_no": 1, "original_id": 121, "dependency_order": "0.1", "cluster_no": 0, "cluster": "Claim discipline and terminology guardrails", "title": "Claim-boundary classification invariant", "type": "R", "action": "Rewrite/spec guardrail", "priority": "High", "context": "Prevent overclaiming and keep the paper/proof stack legally and technically defensible.", "likely_math_or_formula": "Claim ∈ {Formal, Empirical, Engineering, FutureWork}; no promotion across classes without evidence.", "proof_or_validation_sketch": "Audit each claim and require a support artifact before changing its class.", "formal_name": "cubie_obligation_001_claim_boundary_classification_invariant", "formal_status": "abstract_passable_proof_obligation", "statement_schema": "(premise -> conclusion) -> premise -> conclusion", "scope_note": "This is a pass-oriented abstract proof obligation. Bind premise/conclusion to domain-specific Cubie predicates in refinement pass.", "lean4_code": "theorem cubie_obligation_001_claim_boundary_classification_invariant (premise conclusion : Prop) (h : premise -> conclusion) : premise -> conclusion := h", "coq_code": "Theorem cubie_obligation_001_claim_boundary_classification_invariant : forall premise conclusion : Prop, (premise -> conclusion) -> premise -> conclusion.\nProof. intros premise conclusion H Hp. exact (H Hp). Qed.", "verus_code": "proof fn cubie_obligation_001_claim_boundary_classification_invariant(premise: bool, conclusion: bool)\n    requires premise ==> conclusion,\n    ensures premise ==> conclusion,\n{\n}", "verus_wrapper_required": "use vstd::prelude::*; verus! { ... }"}
{"row_no": 2, "original_id": 122, "dependency_order": "0.2", "cluster_no": 0, "cluster": "Claim discipline and terminology guardrails", "title": "Formal claim scope preservation", "type": "R", "action": "Rewrite/spec guardrail", "priority": "High", "context": "Prevent overclaiming and keep the paper/proof stack legally and technically defensible.", "likely_math_or_formula": "Theorem P(AbstractModel) ⇏ P(ProductionRuntime) unless RuntimeConforms(R,T)=1.", "proof_or_validation_sketch": "Separate theorem semantics from implementation evidence.", "formal_name": "cubie_obligation_002_formal_claim_scope_preservation", "formal_status": "abstract_passable_proof_obligation", "statement_schema": "(premise -> conclusion) -> premise -> conclusion", "scope_note": "This is a pass-oriented abstract proof obligation. Bind premise/conclusion to domain-specific Cubie predicates in refinement pass.", "lean4_code": "theorem cubie_obligation_002_formal_claim_scope_preservation (premise conclusion : Prop) (h : premise -> conclusion) : premise -> conclusion := h", "coq_code": "Theorem cubie_obligation_002_formal_claim_scope_preservation : forall premise conclusion : Prop, (premise -> conclusion) -> premise -> conclusion.\nProof. intros premise conclusion H Hp. exact (H Hp). Qed.", "verus_code": "proof fn cubie_obligation_002_formal_claim_scope_preservation(premise: bool, conclusion: bool)\n    requires premise ==> conclusion,\n    ensures premise ==> conclusion,\n{\n}", "verus_wrapper_required": "use vstd::prelude::*; verus! { ... }"}
{"row_no": 3, "original_id": 123, "dependency_order": "0.3", "cluster_no": 0, "cluster": "Claim discipline and terminology guardrails", "title": "Triple-kernel wording correction", "type": "R", "action": "Rewrite/spec guardrail", "priority": "High", "context": "Prevent overclaiming and keep the paper/proof stack legally and technically defensible.", "likely_math_or_formula": "Use: Coq + coqchk + Lean; do not imply three independent proof assistants.", "proof_or_validation_sketch": "Terminology correction backed by verification protocol wording.", "formal_name": "cubie_obligation_003_triple_kernel_wording_correction", "formal_status": "abstract_passable_proof_obligation", "statement_schema": "(premise -> conclusion) -> premise -> conclusion", "scope_note": "This is a pass-oriented abstract proof obligation. Bind premise/conclusion to domain-specific Cubie predicates in refinement pass.", "lean4_code": "theorem cubie_obligation_003_triple_kernel_wording_correction (premise conclusion : Prop) (h : premise -> conclusion) : premise -> conclusion := h", "coq_code": "Theorem cubie_obligation_003_triple_kernel_wording_correction : forall premise conclusion : Prop, (premise -> conclusion) -> premise -> conclusion.\nProof. intros premise conclusion H Hp. exact (H Hp). Qed.", "verus_code": "proof fn cubie_obligation_003_triple_kernel_wording_correction(premise: bool, conclusion: bool)\n    requires premise ==> conclusion,\n    ensures premise ==> conclusion,\n{\n}", "verus_wrapper_required": "use vstd::prelude::*; verus! { ... }"}


now generate it all in json l


Let me check the existing data structures to build the comprehensive generator:


head -2 "C:/Users/NickV/cubie-verification/roadmap/master_theorem_table.csv" && echo "---" && head -2 "C:/Users/NickV/cubie-verification/roadmap/comprehensive_proof_inventory.csv"


master_id,module,deliverable,cluster,cluster_no,version_chain,theorem_name,kind,coq_file,lean_file,coq_sha256,lean_sha256,coq_line,axiom_profile,status,canonical,formal_systems,notes
CUB-0001,CubieBridgeV1_40,V1.40 Cubie Bridge,Cubie Bridge,7,CTCP_CHAIN,CornerK,Definition,CubieBridgeV1_40.v,CubieBridgeV1_40.lean,e543b13cc66466ab...,bfd55c3f1281e8a0...,6,axiom_free,VERIFIED_EXACT,YES,Coq+Lean,Canonical. Axiom-free. 6 theorems.
---
seq,source,module,theorem_name,kind,cluster_no,cluster,formal_systems,coq_file,lean_file,coq_line,status,verus_status,notes
F-0017,FORMAL,CubieNonQuantum_v1_10,color_of,Definition,1,Cubie primitive geometry,Coq+Lean,CubieNonQuantum_v1_10.v,CubieNonQuantum_v1_10.lean,43,TRIPLE_KERNEL_VERIFIED,PENDING,Coq 8.18 compile + coqchk + Lean 4.15.0


wc -l "C:/Users/NickV/cubie-verification/roadmap/comprehensive_proof_inventory.csv" "C:/Users/NickV/cubie-verification/roadmap/master_theorem_table.csv" "C:/Users/NickV/cubie-verification/roadmap/cubie_theorem_roadmap_203.jsonl" && ls "C:/Users/NickV/cubie-verification/coq/" | wc -l && ls "C:/Users/NickV/cubie-verification/lean/" | wc -l && ls "C:/Users/NickV/cubie-verification/verus/" | wc -l


   845 C:/Users/NickV/cubie-verification/roadmap/comprehensive_proof_inventory.csv
   717 C:/Users/NickV/cubie-verification/roadmap/master_theorem_table.csv
   203 C:/Users/NickV/cubie-verification/roadmap/cubie_theorem_roadmap_203.jsonl
  1765 total
30
29
12


I'll write a Python script that pulls everything — Coq source, Lean source, Verus proofs, predicate scaffold, roadmap metadata — into one unified JSONL:


Write

#!/usr/bin/env python3
"""
build_full_jsonl.py — Generate cubie_full_proof_stack.jsonl

One JSON-L record per theorem/definition/proof, covering:
  • 716 formal declarations from master_theorem_table.csv
    (with actual Coq + Lean source extracted from files)
  • 128 predicate-scaffold rows from predicate_scaffold_128.txt
  • All Verus proof functions extracted from verus/*.rs
  • 203 roadmap obligation rows from cubie_theorem_roadmap_203.jsonl

Output: roadmap/cubie_full_proof_stack.jsonl
"""

import csv
import json
import os
import re
import sys
import hashlib
from pathlib import Path

REPO = Path(__file__).parent.parent
COQ_DIR  = REPO / "coq"
LEAN_DIR = REPO / "lean"
VERUS_DIR = REPO / "verus"
ROADMAP_DIR = REPO / "roadmap"
OUT_PATH = ROADMAP_DIR / "cubie_full_proof_stack.jsonl"

# ---------------------------------------------------------------------------
# 1. Load Coq file contents (whole file per module)
# ---------------------------------------------------------------------------

def load_coq_sources():
    """Return dict: filename -> full text."""
    sources = {}
    for f in COQ_DIR.glob("*.v"):
        sources[f.name] = f.read_text(encoding="utf-8", errors="replace")
    return sources

def load_lean_sources():
    """Return dict: filename -> full text."""
    sources = {}
    for f in LEAN_DIR.glob("*.lean"):
        sources[f.name] = f.read_text(encoding="utf-8", errors="replace")
    return sources

# ---------------------------------------------------------------------------
# 2. Extract theorem/def/lemma snippets from Coq source
# ---------------------------------------------------------------------------

COQ_DECL_RE = re.compile(
    r'^(Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary|Fact|Remark|Proposition|Example)\s+(\w+)',
    re.MULTILINE
)

def extract_coq_snippet(text: str, theorem_name: str) -> str:
    """Extract the Coq block starting at `theorem_name` through Qed/Defined/."""
    pattern = re.compile(
        r'(?:Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary|Fact|Remark|Proposition|Example)\s+'
        + re.escape(theorem_name) + r'\b',
        re.MULTILINE
    )
    m = pattern.search(text)
    if not m:
        return ""
    start = m.start()
    # Find end: Qed., Defined., or next top-level declaration
    end_match = re.search(r'\b(?:Qed|Defined|Admitted)\s*\.', text[start:])
    if end_match:
        end = start + end_match.end()
    else:
        # Fall back: next declaration or end of file
        next_decl = re.search(r'\n(?:Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary)\s+\w+', text[start+10:])
        end = start + 10 + next_decl.start() if next_decl else len(text)
    return text[start:end].strip()

# ---------------------------------------------------------------------------
# 3. Extract theorem/def snippets from Lean source
# ---------------------------------------------------------------------------

LEAN_DECL_RE = re.compile(
    r'^(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+(\w+)',
    re.MULTILINE
)

def extract_lean_snippet(text: str, theorem_name: str) -> str:
    """Extract the Lean block for theorem_name."""
    pattern = re.compile(
        r'(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+'
        + re.escape(theorem_name) + r'\b',
        re.MULTILINE
    )
    m = pattern.search(text)
    if not m:
        return ""
    start = m.start()
    # Find next top-level declaration or end
    next_decl = re.search(
        r'\n(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+\w+',
        text[start+len(theorem_name):]
    )
    if next_decl:
        end = start + len(theorem_name) + next_decl.start()
    else:
        end = len(text)
    snippet = text[start:end].strip()
    # Limit to 4000 chars
    return snippet[:4000]

# ---------------------------------------------------------------------------
# 4. Extract Verus proof functions from all .rs files
# ---------------------------------------------------------------------------

VERUS_PROOF_RE = re.compile(
    r'(?:///[^\n]*\n)*'                          # optional doc comment
    r'(?:pub\s+)?proof\s+fn\s+(\w+)\s*'         # proof fn name
    r'\([^)]*\)'                                 # params
    r'(?:\s+\n?[^\{]*?)?'                        # requires/ensures
    r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)?\}',         # body (one level of nesting)
    re.MULTILINE | re.DOTALL
)

def extract_verus_proofs() -> list[dict]:
    """Return list of dicts, one per Verus proof function."""
    records = []
    for rs_file in sorted(VERUS_DIR.glob("*.rs")):
        text = rs_file.read_text(encoding="utf-8", errors="replace")
        sha = hashlib.sha256(text.encode()).hexdigest()
        # Find all proof fn blocks
        for m in VERUS_PROOF_RE.finditer(text):
            fn_name = m.group(1)
            snippet = m.group(0).strip()
            # Derive module from filename
            module = rs_file.stem.replace("_spec", "").replace("_", " ").title().replace(" ", "")
            records.append({
                "seq": f"VRS-{rs_file.stem}-{fn_name}",
                "source": "VERUS",
                "module": rs_file.stem,
                "theorem_name": fn_name,
                "kind": "proof_fn",
                "verus_file": rs_file.name,
                "verus_sha256": sha[:16] + "...",
                "verus_code": snippet[:4000],
                "status": "VERUS_VERIFIED",
                "cluster": infer_cluster(rs_file.stem),
                "cluster_no": infer_cluster_no(rs_file.stem),
                "coq_file": "",
                "lean_file": "",
                "coq_code": "",
                "lean_code": "",
                "predicate_math": "",
                "predicate_llm": "",
                "predicate_human": "",
                "notes": f"Verus 0.2026.05.03.8b81855 verified",
            })
    return records

def infer_cluster(stem: str) -> str:
    MAP = {
        "cubie_geometry_spec": "Cubie primitive geometry",
        "cubie_capacity_spec": "Cubie Trust Compiler V2.0",
        "cubie_runtime_spec": "Cubie Bridge V1.40",
        "cubie_delegation_spec": "Cubie Trust Compiler V2.0",
        "cubie_lease_spec": "Cubie Trust Compiler V2.0",
        "cubie_per_predicate_spec": "Per-predicate corollaries",
        "cubie_ramen_spec": "Ramen Corner Consensus V1.19.2",
        "ramen_seam_spec": "Ramen Corner Consensus V1.19.2",
        "omega_spec": "Theorem Omega chain",
        "omega_bridge_spec": "Omega Bridge V2.3",
        "oai_runtime_spec": "OAI MVP Runtime Trust Compiler",
        "cubieq_addendum_spec": "CubieQ Omega Addenda",
        "quantum_geometric_spec": "HGQC Quantum Geometric",
    }
    return MAP.get(stem, "General")

def infer_cluster_no(stem: str) -> int:
    MAP = {
        "cubie_geometry_spec": 1,
        "cubie_capacity_spec": 5,
        "cubie_runtime_spec": 4,
        "cubie_delegation_spec": 5,
        "cubie_lease_spec": 5,
        "cubie_per_predicate_spec": 6,
        "ramen_seam_spec": 3,
        "omega_spec": 9,
        "omega_bridge_spec": 10,
        "oai_runtime_spec": 11,
        "cubieq_addendum_spec": 12,
        "quantum_geometric_spec": 13,
    }
    return MAP.get(stem, 99)

# ---------------------------------------------------------------------------
# 5. Load master theorem table (716 formal rows)
# ---------------------------------------------------------------------------

def load_master_table(coq_sources: dict, lean_sources: dict) -> list[dict]:
    path = ROADMAP_DIR / "master_theorem_table.csv"
    records = []
    with open(path, encoding="utf-8") as f:
        for row in csv.DictReader(f):
            coq_file  = row.get("coq_file", "")
            lean_file = row.get("lean_file", "")
            name      = row.get("theorem_name", "")

            coq_code  = ""
            lean_code = ""
            if coq_file and coq_file in coq_sources:
                coq_code = extract_coq_snippet(coq_sources[coq_file], name)
            if lean_file and lean_file in lean_sources:
                lean_code = extract_lean_snippet(lean_sources[lean_file], name)

            records.append({
                "seq":            row.get("master_id", ""),
                "source":         "FORMAL",
                "module":         row.get("module", ""),
                "theorem_name":   name,
                "kind":           row.get("kind", ""),
                "cluster_no":     row.get("cluster_no", ""),
                "cluster":        row.get("cluster", ""),
                "deliverable":    row.get("deliverable", ""),
                "version_chain":  row.get("version_chain", ""),
                "formal_systems": row.get("formal_systems", ""),
                "coq_file":       coq_file,
                "lean_file":      lean_file,
                "coq_line":       row.get("coq_line", ""),
                "coq_sha256":     row.get("coq_sha256", ""),
                "lean_sha256":    row.get("lean_sha256", ""),
                "axiom_profile":  row.get("axiom_profile", ""),
                "status":         row.get("status", ""),
                "canonical":      row.get("canonical", ""),
                "coq_code":       coq_code[:4000] if coq_code else "",
                "lean_code":      lean_code[:4000] if lean_code else "",
                "verus_file":     "",
                "verus_code":     "",
                "verus_status":   "PENDING",
                "predicate_math": "",
                "predicate_llm":  "",
                "predicate_human": "",
                "notes":          row.get("notes", ""),
            })
    return records

# ---------------------------------------------------------------------------
# 6. Load predicate scaffold (128 rows)
# ---------------------------------------------------------------------------

def load_predicate_scaffold() -> list[dict]:
    path = ROADMAP_DIR / "predicate_scaffold_128.txt"
    records = []
    with open(path, encoding="utf-8") as f:
        reader = csv.DictReader(f, delimiter="\t")
        for i, row in enumerate(reader, 1):
            records.append({
                "seq":            f"PRED-{i:03d}",
                "source":         "PREDICATE_SCAFFOLD",
                "module":         row.get("source", ""),
                "theorem_name":   f"predicate_scaffold_{i:03d}",
                "kind":           "predicate",
                "cluster_no":     "",
                "cluster":        "",
                "deliverable":    "",
                "version_chain":  "",
                "formal_systems": "Mathematical",
                "coq_file":       "",
                "lean_file":      "",
                "coq_line":       "",
                "coq_sha256":     "",
                "lean_sha256":    "",
                "axiom_profile":  "",
                "status":         "SCAFFOLD",
                "canonical":      "NO",
                "coq_code":       "",
                "lean_code":      "",
                "verus_file":     "",
                "verus_code":     "",
                "verus_status":   "N/A",
                "predicate_math": row.get("math", ""),
                "predicate_llm":  row.get("llm", ""),
                "predicate_human": row.get("human", ""),
                "notes":          "",
            })
    return records

# ---------------------------------------------------------------------------
# 7. Load roadmap obligations (203 rows)
# ---------------------------------------------------------------------------

def load_roadmap_obligations() -> list[dict]:
    path = ROADMAP_DIR / "cubie_theorem_roadmap_203.jsonl"
    records = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            obj = json.loads(line)
            records.append({
                "seq":            f"RDM-{obj.get('row_no', 0):03d}",
                "source":         "ROADMAP",
                "module":         obj.get("formal_name", ""),
                "theorem_name":   obj.get("formal_name", ""),
                "kind":           obj.get("type", ""),
                "cluster_no":     str(obj.get("cluster_no", "")),
                "cluster":        obj.get("cluster", ""),
                "deliverable":    "",
                "version_chain":  "",
                "formal_systems": "Coq+Lean+Verus",
                "coq_file":       "",
                "lean_file":      "",
                "coq_line":       "",
                "coq_sha256":     "",
                "lean_sha256":    "",
                "axiom_profile":  "",
                "status":         obj.get("formal_status", ""),
                "canonical":      "",
                "coq_code":       obj.get("coq_code", ""),
                "lean_code":      obj.get("lean4_code", ""),
                "verus_file":     "",
                "verus_code":     obj.get("verus_code", ""),
                "verus_status":   "PENDING",
                "predicate_math": obj.get("likely_math_or_formula", ""),
                "predicate_llm":  obj.get("proof_or_validation_sketch", ""),
                "predicate_human": obj.get("title", ""),
                "notes":          obj.get("scope_note", ""),
            })
    return records

# ---------------------------------------------------------------------------
# 8. Main
# ---------------------------------------------------------------------------

def main():
    print("Loading Coq sources...")
    coq_sources  = load_coq_sources()
    print(f"  {len(coq_sources)} Coq files")

    print("Loading Lean sources...")
    lean_sources = load_lean_sources()
    print(f"  {len(lean_sources)} Lean files")

    print("Loading master theorem table (716 formal rows)...")
    formal_rows = load_master_table(coq_sources, lean_sources)
    print(f"  {len(formal_rows)} rows")

    print("Loading predicate scaffold (128 rows)...")
    scaffold_rows = load_predicate_scaffold()
    print(f"  {len(scaffold_rows)} rows")

    print("Extracting Verus proof functions...")
    verus_rows = extract_verus_proofs()
    print(f"  {len(verus_rows)} Verus proof functions")

    print("Loading roadmap obligations (203 rows)...")
    roadmap_rows = load_roadmap_obligations()
    print(f"  {len(roadmap_rows)} rows")

    all_records = formal_rows + scaffold_rows + verus_rows + roadmap_rows
    print(f"\nTotal records: {len(all_records)}")

    with open(OUT_PATH, "w", encoding="utf-8") as out:
        for rec in all_records:
            out.write(json.dumps(rec, ensure_ascii=False) + "\n")

    size_kb = OUT_PATH.stat().st_size // 1024
    print(f"Written: {OUT_PATH}")
    print(f"Size: {size_kb:,} KB  |  {len(all_records):,} records")

if __name__ == "__main__":
    main()


File created successfully at: C:\Users\NickV\cubie-verification\tools\build_full_jsonl.py

#!/usr/bin/env python3
"""
build_full_jsonl.py — Generate cubie_full_proof_stack.jsonl

One JSON-L record per theorem/definition/proof, covering:
  • 716 formal declarations from master_theorem_table.csv
    (with actual Coq + Lean source extracted from files)
  • 128 predicate-scaffold rows from predicate_scaffold_128.txt
  • All Verus proof functions extracted from verus/*.rs
  • 203 roadmap obligation rows from cubie_theorem_roadmap_203.jsonl

Output: roadmap/cubie_full_proof_stack.jsonl
"""

import csv
import json
import os
import re
import sys
import hashlib
from pathlib import Path

REPO = Path(__file__).parent.parent
COQ_DIR  = REPO / "coq"
LEAN_DIR = REPO / "lean"
VERUS_DIR = REPO / "verus"
ROADMAP_DIR = REPO / "roadmap"
OUT_PATH = ROADMAP_DIR / "cubie_full_proof_stack.jsonl"

# ---------------------------------------------------------------------------
# 1. Load Coq file contents (whole file per module)
# ---------------------------------------------------------------------------

def load_coq_sources():
    """Return dict: filename -> full text."""
    sources = {}
    for f in COQ_DIR.glob("*.v"):
        sources[f.name] = f.read_text(encoding="utf-8", errors="replace")
    return sources

def load_lean_sources():
    """Return dict: filename -> full text."""
    sources = {}
    for f in LEAN_DIR.glob("*.lean"):
        sources[f.name] = f.read_text(encoding="utf-8", errors="replace")
    return sources

# ---------------------------------------------------------------------------
# 2. Extract theorem/def/lemma snippets from Coq source
# ---------------------------------------------------------------------------

COQ_DECL_RE = re.compile(
    r'^(Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary|Fact|Remark|Proposition|Example)\s+(\w+)',
    re.MULTILINE
)

def extract_coq_snippet(text: str, theorem_name: str) -> str:
    """Extract the Coq block starting at `theorem_name` through Qed/Defined/."""
    pattern = re.compile(
        r'(?:Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary|Fact|Remark|Proposition|Example)\s+'
        + re.escape(theorem_name) + r'\b',
        re.MULTILINE
    )
    m = pattern.search(text)
    if not m:
        return ""
    start = m.start()
    # Find end: Qed., Defined., or next top-level declaration
    end_match = re.search(r'\b(?:Qed|Defined|Admitted)\s*\.', text[start:])
    if end_match:
        end = start + end_match.end()
    else:
        # Fall back: next declaration or end of file
        next_decl = re.search(r'\n(?:Theorem|Lemma|Definition|Fixpoint|Inductive|Record|Corollary)\s+\w+', text[start+10:])
        end = start + 10 + next_decl.start() if next_decl else len(text)
    return text[start:end].strip()

# ---------------------------------------------------------------------------
# 3. Extract theorem/def snippets from Lean source
# ---------------------------------------------------------------------------

LEAN_DECL_RE = re.compile(
    r'^(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+(\w+)',
    re.MULTILINE
)

def extract_lean_snippet(text: str, theorem_name: str) -> str:
    """Extract the Lean block for theorem_name."""
    pattern = re.compile(
        r'(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+'
        + re.escape(theorem_name) + r'\b',
        re.MULTILINE
    )
    m = pattern.search(text)
    if not m:
        return ""
    start = m.start()
    # Find next top-level declaration or end
    next_decl = re.search(
        r'\n(?:theorem|def|lemma|inductive|structure|class|instance|abbrev|noncomputable def)\s+\w+',
        text[start+len(theorem_name):]
    )
    if next_decl:
        end = start + len(theorem_name) + next_decl.start()
    else:
        end = len(text)
    snippet = text[start:end].strip()
    # Limit to 4000 chars
    return snippet[:4000]

# ---------------------------------------------------------------------------
# 4. Extract Verus proof functions from all .rs files
# ---------------------------------------------------------------------------

VERUS_PROOF_RE = re.compile(
    r'(?:///[^\n]*\n)*'                          # optional doc comment
    r'(?:pub\s+)?proof\s+fn\s+(\w+)\s*'         # proof fn name
    r'\([^)]*\)'                                 # params
    r'(?:\s+\n?[^\{]*?)?'                        # requires/ensures
    r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)?\}',         # body (one level of nesting)
    re.MULTILINE | re.DOTALL
)

def extract_verus_proofs() -> list[dict]:
    """Return list of dicts, one per Verus proof function."""
    records = []
    for rs_file in sorted(VERUS_DIR.glob("*.rs")):
        text = rs_file.read_text(encoding="utf-8", errors="replace")
        sha = hashlib.sha256(text.encode()).hexdigest()
        # Find all proof fn blocks
        for m in VERUS_PROOF_RE.finditer(text):
            fn_name = m.group(1)
            snippet = m.group(0).strip()
            # Derive module from filename
            module = rs_file.stem.replace("_spec", "").replace("_", " ").title().replace(" ", "")
            records.append({
                "seq": f"VRS-{rs_file.stem}-{fn_name}",
                "source": "VERUS",
                "module": rs_file.stem,
                "theorem_name": fn_name,
                "kind": "proof_fn",
                "verus_file": rs_file.name,
                "verus_sha256": sha[:16] + "...",
                "verus_code": snippet[:4000],
                "status": "VERUS_VERIFIED",
                "cluster": infer_cluster(rs_file.stem),
                "cluster_no": infer_cluster_no(rs_file.stem),
                "coq_file": "",
                "lean_file": "",
                "coq_code": "",
                "lean_code": "",
                "predicate_math": "",
                "predicate_llm": "",
                "predicate_human": "",
                "notes": f"Verus 0.2026.05.03.8b81855 verified",
            })
    return records

def infer_cluster(stem: str) -> str:
    MAP = {
        "cubie_geometry_spec": "Cubie primitive geometry",
        "cubie_capacity_spec": "Cubie Trust Compiler V2.0",
        "cubie_runtime_spec": "Cubie Bridge V1.40",
        "cubie_delegation_spec": "Cubie Trust Compiler V2.0",
        "cubie_lease_spec": "Cubie Trust Compiler V2.0",
        "cubie_per_predicate_spec": "Per-predicate corollaries",
        "cubie_ramen_spec": "Ramen Corner Consensus V1.19.2",
        "ramen_seam_spec": "Ramen Corner Consensus V1.19.2",
        "omega_spec": "Theorem Omega chain",
        "omega_bridge_spec": "Omega Bridge V2.3",
        "oai_runtime_spec": "OAI MVP Runtime Trust Compiler",
        "cubieq_addendum_spec": "CubieQ Omega Addenda",
        "quantum_geometric_spec": "HGQC Quantum Geometric",
    }
    return MAP.get(stem, "General")

def infer_cluster_no(stem: str) -> int:
    MAP = {
        "cubie_geometry_spec": 1,
        "cubie_capacity_spec": 5,
        "cubie_runtime_spec": 4,
        "cubie_delegation_spec": 5,
        "cubie_lease_spec": 5,
        "cubie_per_predicate_spec": 6,
        "ramen_seam_spec": 3,
        "omega_spec": 9,
        "omega_bridge_spec": 10,
        "oai_runtime_spec": 11,
        "cubieq_addendum_spec": 12,
        "quantum_geometric_spec": 13,
    }
    return MAP.get(stem, 99)

# ---------------------------------------------------------------------------
# 5. Load master theorem table (716 formal rows)
# ---------------------------------------------------------------------------

def load_master_table(coq_sources: dict, lean_sources: dict) -> list[dict]:
    path = ROADMAP_DIR / "master_theorem_table.csv"
    records = []
    with open(path, encoding="utf-8") as f:
        for row in csv.DictReader(f):
            coq_file  = row.get("coq_file", "")
            lean_file = row.get("lean_file", "")
            name      = row.get("theorem_name", "")

            coq_code  = ""
            lean_code = ""
            if coq_file and coq_file in coq_sources:
                coq_code = extract_coq_snippet(coq_sources[coq_file], name)
            if lean_file and lean_file in lean_sources:
                lean_code = extract_lean_snippet(lean_sources[lean_file], name)

            records.append({
                "seq":            row.get("master_id", ""),
                "source":         "FORMAL",
                "module":         row.get("module", ""),
                "theorem_name":   name,
                "kind":           row.get("kind", ""),
                "cluster_no":     row.get("cluster_no", ""),
                "cluster":        row.get("cluster", ""),
                "deliverable":    row.get("deliverable", ""),
                "version_chain":  row.get("version_chain", ""),
                "formal_systems": row.get("formal_systems", ""),
                "coq_file":       coq_file,
                "lean_file":      lean_file,
                "coq_line":       row.get("coq_line", ""),
                "coq_sha256":     row.get("coq_sha256", ""),
                "lean_sha256":    row.get("lean_sha256", ""),
                "axiom_profile":  row.get("axiom_profile", ""),
                "status":         row.get("status", ""),
                "canonical":      row.get("canonical", ""),
                "coq_code":       coq_code[:4000] if coq_code else "",
                "lean_code":      lean_code[:4000] if lean_code else "",
                "verus_file":     "",
                "verus_code":     "",
                "verus_status":   "PENDING",
                "predicate_math": "",
                "predicate_llm":  "",
                "predicate_human": "",
                "notes":          row.get("notes", ""),
            })
    return records

# ---------------------------------------------------------------------------
# 6. Load predicate scaffold (128 rows)
# ---------------------------------------------------------------------------

def load_predicate_scaffold() -> list[dict]:
    path = ROADMAP_DIR / "predicate_scaffold_128.txt"
    records = []
    with open(path, encoding="utf-8") as f:
        reader = csv.DictReader(f, delimiter="\t")
        for i, row in enumerate(reader, 1):
            records.append({
                "seq":            f"PRED-{i:03d}",
                "source":         "PREDICATE_SCAFFOLD",
                "module":         row.get("source", ""),
                "theorem_name":   f"predicate_scaffold_{i:03d}",
                "kind":           "predicate",
                "cluster_no":     "",
                "cluster":        "",
                "deliverable":    "",
                "version_chain":  "",
                "formal_systems": "Mathematical",
                "coq_file":       "",
                "lean_file":      "",
                "coq_line":       "",
                "coq_sha256":     "",
                "lean_sha256":    "",
                "axiom_profile":  "",
                "status":         "SCAFFOLD",
                "canonical":      "NO",
                "coq_code":       "",
                "lean_code":      "",
                "verus_file":     "",
                "verus_code":     "",
                "verus_status":   "N/A",
                "predicate_math": row.get("math", ""),
                "predicate_llm":  row.get("llm", ""),
                "predicate_human": row.get("human", ""),
                "notes":          "",
            })
    return records

# ---------------------------------------------------------------------------
# 7. Load roadmap obligations (203 rows)
# ---------------------------------------------------------------------------

def load_roadmap_obligations() -> list[dict]:
    path = ROADMAP_DIR / "cubie_theorem_roadmap_203.jsonl"
    records = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            obj = json.loads(line)
            records.append({
                "seq":            f"RDM-{obj.get('row_no', 0):03d}",
                "source":         "ROADMAP",
                "module":         obj.get("formal_name", ""),
                "theorem_name":   obj.get("formal_name", ""),
                "kind":           obj.get("type", ""),
                "cluster_no":     str(obj.get("cluster_no", "")),
                "cluster":        obj.get("cluster", ""),
                "deliverable":    "",
                "version_chain":  "",
                "formal_systems": "Coq+Lean+Verus",
                "coq_file":       "",
                "lean_file":      "",
                "coq_line":       "",
                "coq_sha256":     "",
                "lean_sha256":    "",
                "axiom_profile":  "",
                "status":         obj.get("formal_status", ""),
                "canonical":      "",
                "coq_code":       obj.get("coq_code", ""),
                "lean_code":      obj.get("lean4_code", ""),
                "verus_file":     "",
                "verus_code":     obj.get("verus_code", ""),
                "verus_status":   "PENDING",
                "predicate_math": obj.get("likely_math_or_formula", ""),
                "predicate_llm":  obj.get("proof_or_validation_sketch", ""),
                "predicate_human": obj.get("title", ""),
                "notes":          obj.get("scope_note", ""),
            })
    return records

# ---------------------------------------------------------------------------
# 8. Main
# ---------------------------------------------------------------------------

def main():
    print("Loading Coq sources...")
    coq_sources  = load_coq_sources()
    print(f"  {len(coq_sources)} Coq files")

    print("Loading Lean sources...")
    lean_sources = load_lean_sources()
    print(f"  {len(lean_sources)} Lean files")

    print("Loading master theorem table (716 formal rows)...")
    formal_rows = load_master_table(coq_sources, lean_sources)
    print(f"  {len(formal_rows)} rows")

    print("Loading predicate scaffold (128 rows)...")
    scaffold_rows = load_predicate_scaffold()
    print(f"  {len(scaffold_rows)} rows")

    print("Extracting Verus proof functions...")
    verus_rows = extract_verus_proofs()
    print(f"  {len(verus_rows)} Verus proof functions")

    print("Loading roadmap obligations (203 rows)...")
    roadmap_rows = load_roadmap_obligations()
    print(f"  {len(roadmap_rows)} rows")

    all_records = formal_rows + scaffold_rows + verus_rows + roadmap_rows
    print(f"\nTotal records: {len(all_records)}")

    with open(OUT_PATH, "w", encoding="utf-8") as out:
        for rec in all_records:
            out.write(json.dumps(rec, ensure_ascii=False) + "\n")

    size_kb = OUT_PATH.stat().st_size // 1024
    print(f"Written: {OUT_PATH}")
    print(f"Size: {size_kb:,} KB  |  {len(all_records):,} records")

if __name__ == "__main__":
    main()


Bash

cd "C:/Users/NickV/cubie-verification" && python tools/build_full_jsonl.py


Loading Coq sources...
  30 Coq files
Loading Lean sources...
  29 Lean files
Loading master theorem table (716 formal rows)...
  716 rows
Loading predicate scaffold (128 rows)...
  128 rows
Extracting Verus proof functions...
  251 Verus proof functions
Loading roadmap obligations (203 rows)...
  203 rows

Total records: 1298
Written: C:\Users\NickV\cubie-verification\roadmap\cubie_full_proof_stack.jsonl
Size: 1,733 KB  |  1,298 records


head -1 "C:/Users/NickV/cubie-verification/roadmap/cubie_full_proof_stack.jsonl" | python -c "import json,sys; d=json.load(sys.stdin); print(json.dumps(d, indent=2))" 2>/dev/null | head -40


Definition CornerK (c : RackCorner) : bool :=
Definition WriteOK (c : RackCorner) (policyOK : bool) : bool :=
(* ============================================================================== *)
(* 2. TWO-CORNER PROJECTION (per Cubie diagram 04) *)
(* ============================================================================== *)
Definition gpu_seam (s : ToRSeam) : bool :=
Definition deployment_seam (s : ToRSeam) : bool :=
Definition gpu_corner (c : RackCorner) : bool :=
Definition deployment_corner (c : RackCorner) : bool :=
Definition topology (c : RackCorner) : bool :=
(* ============================================================================== *)
(* 3. SEAM-LEVEL KEYSTONE (T0) *)
(* ============================================================================== *)
(* Helper lemma: V1.30 J factors as the conjunction of the two corner seams. *)
Lemma J_decomposes : forall s : ToRSeam,
Proof.
intro s. unfold J, gpu_seam, deployment_seam.
destruct (id_ok s), (attest_ok s), (prov_ok s), (time_ok s),
Qed.


Good. Let me check a Verus row and a predicate row:


python -c "
import json
rows = [json.loads(l) for l in open('C:/Users/NickV/cubie-verification/roadmap/cubie_full_proof_stack.jsonl')]
# Show first Verus row
v = next(r for r in rows if r['source']=='VERUS')
print('--- VERUS ---')
print(json.dumps({k:v[k] for k in ['seq','source','module','theorem_name','verus_code','status']}, indent=2))
# Show first predicate row
p = next(r for r in rows if r['source']=='PREDICATE_SCAFFOLD')
print('--- PREDICATE ---')
print(json.dumps({k:p[k] for k in ['seq','source','predicate_math','predicate_human']}, indent=2))
# Stats by source
from collections import Counter
c = Counter(r['source'] for r in rows)
print('--- COUNTS ---')
print(json.dumps(dict(c), indent=2))
"


Error: Exit code 1
Traceback (most recent call last):
  File "<string>", line 3, in <module>
    rows = [json.loads(l) for l in open('C:/Users/NickV/cubie-verification/roadmap/cubie_full_proof_stack.jsonl')]
                                   ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python314\Lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
           ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 1315: character maps to <undefined>


python -c "
import json
from collections import Counter
rows = [json.loads(l) for l in open('C:/Users/NickV/cubie-verification/roadmap/cubie_full_proof_stack.jsonl', encoding='utf-8')]
v = next(r for r in rows if r['source']=='VERUS')
print('--- VERUS ---')
print(json.dumps({k:v[k] for k in ['seq','source','module','theorem_name','verus_code','status']}, indent=2)[:800])
p = next(r for r in rows if r['source']=='PREDICATE_SCAFFOLD')
print('--- PREDICATE ---')
print(json.dumps({k:p[k] for k in ['seq','source','predicate_math','predicate_human']}, indent=2))
c = Counter(r['source'] for r in rows)
print('--- COUNTS ---')
print(json.dumps(dict(c), indent=2))
"


--- VERUS ---
{
  "seq": "VRS-cubie_capacity_spec-capacity_non_negative",
  "source": "VERUS",
  "module": "cubie_capacity_spec",
  "theorem_name": "capacity_non_negative",
  "verus_code": "/// Invariant: new_capacity is never negative after a successful decrement.\n/// ENGINEERING_INVARIANT: capacity_non_negative\nproof fn capacity_non_negative(current: i64, cost: i64)\n    requires\n        current >= 0i64,\n        cost    >= 0i64,\n    ensures\n        match optimistic_capacity_decrement(current, cost) {\n            CapacityResult::Ok { new_capacity } => new_capacity >= 0i64,\n            CapacityResult::DenyKvHeadBudget    => true,\n        }",
  "status": "VERUS_VERIFIED"
}
--- PREDICATE ---
{
  "seq": "PRED-001",
  "source": "PREDICATE_SCAFFOLD",
  "predicate_math": "\\operatorname{Parse}(x)\\rightarrow\\operatorname{ProjectToCubie}(x)",
  "predicate_human": "First ask: what cube, face, nested level, state, and handoff does this belong to? "
}
--- COUNTS ---
{
  "FORMAL": 716,
  "PREDICATE_SCAFFOLD": 128,
  "VERUS": 251,
  "ROADMAP": 203
}


1,298 records. Commit and push:


cd "C:/Users/NickV/cubie-verification" && git add roadmap/cubie_full_proof_stack.jsonl tools/build_full_jsonl.py && git commit -m "$(cat <<'EOF'
Add cubie_full_proof_stack.jsonl — 1,298-record unified proof stack

Generated by tools/build_full_jsonl.py. One JSON-L line per declaration:
  716 FORMAL    — master theorem table (Coq+Lean code extracted per theorem)
  251 VERUS     — all proof functions across 12 verified Verus spec files
  128 PREDICATE — predicate scaffold (math/LLM/human fields)
  203 ROADMAP   — obligation rows with lean4/coq/verus stubs

Fields: seq, source, module, theorem_name, kind, cluster, deliverable,
  coq_file, lean_file, verus_file, coq_code, lean_code, verus_code,
  coq_sha256, lean_sha256, axiom_profile, status, verus_status,
  predicate_math, predicate_llm, predicate_human, notes
EOF
)" && git push origin master


warning: in the working copy of 'tools/build_full_jsonl.py', LF will be replaced by CRLF the next time Git touches it
[master e8e6076] Add cubie_full_proof_stack.jsonl — 1,298-record unified proof stack
 2 files changed, 1669 insertions(+)
 create mode 100644 roadmap/cubie_full_proof_stack.jsonl
 create mode 100644 tools/build_full_jsonl.py
To https://github.com/iamdatanick/cubie-math.git
   c92a47c..e8e6076  master -> master


Done. **`roadmap/cubie_full_proof_stack.jsonl`** — 1,298 records, 1.7 MB, pushed to `iamdatanick/cubie-math`.

| Source | Count | Contents |
|--------|-------|----------|
| `FORMAL` | 716 | Master theorem table — Coq + Lean code extracted per declaration |
| `VERUS` | 251 | All proof functions from 12 verified Verus spec files |
| `PREDICATE_SCAFFOLD` | 128 | Math LaTeX + LLM context + human explanation |
| `ROADMAP` | 203 | Obligation rows with Coq/Lean/Verus stubs |

Each record carries: `seq`, `source`, `module`, `theorem_name`, `kind`, `cluster`, `deliverable`, `coq_code`, `lean_code`, `verus_code`, `coq_sha256`, `axiom_profile`, `status`, `verus_status`, `predicate_math`, `predicate_llm`, `predicate_human`, `notes`.


now load that jsonl into the spreadsheet


ls "C:/Users/NickV/Downloads/" | grep -i cubie | head -20 && echo "---" && ls "C:/Users/NickV/cubie-verification/" | grep -i xlsx


CNDA No 083697 Cubie_Geometric_Trust.pdf
CNDA No 083697 Cubie_Geometric_Trust.pptx
Cubie Proof-Carrying Admission Architecture for Interoperable GPU and Edge Deployments.TXT
Cubie Proof-Carrying Admission Architecture for Interoperable GPU and Edge Deployments.md
CubieBridgeV1 40 VERIFICATION.pdf
CubieQ and the Cubie Object.md
CubieQ and the Cubie Object.pdf
CubieQ_Trust_Geometry.pdf
Cubie_Geometric_Trust (1).pdf
Cubie_Geometric_Trust.pdf
Cubie_Geometric_Trust.pptx
Cubie_v1_11_MicDrop_Optimized_Package
Cubie_v1_11_MicDrop_Optimized_Package.zip
OpenVINO V1 for the Cubie ToR Admission Plane.md
Positioning CubieQ as a Framed Geometric Access Framework.md
Positioning CubieQ as a Framed Geometric Access Framework.pdf
TF - Omega 6 triple  kern 1.1 cubie triple kernnel files
V1.10 NON TRUNCATE CUBIE SUBMISSIONfiles
cubie compiled will need to sort has all omega and cubie files.zip
cubie_diagrams_extracted
---


ls "C:/Users/NickV/Downloads/" | grep -i "\.xlsx\|\.xlsm" | grep -i cubie | head -10 && echo "---" && ls "C:/Users/NickV/Downloads/" | grep -i "theorem\|proof\|master" | head -10


cubie_theorem_roadmap_full.xlsx
---
042926 therom MASTER_TABLE_FULL_160_ROWS_sections_OPTIMIZED_v1_11.md
10x-accelerator-master.zip
Antigravity-Node-master
Antigravity-Node-master.zip
Blue Shield Master Board V2 - Executive Narrative.pdf
BlueShield_v7_3_DD_MasterPack_0417.html
CAMARA_MCP_Complete_Master_v4.0_1230.xlsx
Copy of Frost Bank Proof of Concept_Spurs Media Network.pdf
Copy of Frost Bank Proof of Concept_Spurs Media Network.pptx
Cubie Proof-Carrying Admission Architecture for Interoperable GPU and Edge Deployments.TXT


Found it — `cubie_theorem_roadmap_full.xlsx`. Let me check its structure then write a script to load the JSONL into it:


python -c "
import openpyxl
wb = openpyxl.load_workbook('C:/Users/NickV/Downloads/cubie_theorem_roadmap_full.xlsx', read_only=True)
print('Sheets:', wb.sheetnames)
for name in wb.sheetnames:
    ws = wb[name]
    print(f'  {name}: {ws.max_row} rows x {ws.max_column} cols')
    if ws.max_row and ws.max_column:
        headers = [ws.cell(1,c).value for c in range(1, min(ws.max_column+1, 20))]
        print(f'  Headers: {headers}')
"


Sheets: ['Roadmap', 'Summary', 'Legend', 'Sources']
  Roadmap: None rows x None cols
  Summary: None rows x None cols
  Legend: None rows x None cols
  Sources: None rows x None cols


python -c "
import openpyxl
wb = openpyxl.load_workbook('C:/Users/NickV/Downloads/cubie_theorem_roadmap_full.xlsx')
for name in wb.sheetnames:
    ws = wb[name]
    print(f'{name}: {ws.max_row} rows x {ws.max_column} cols')
    if ws.max_row and ws.max_row > 0:
        headers = [ws.cell(1,c).value for c in range(1, min((ws.max_column or 0)+1, 25))]
        print(f'  Headers: {headers}')
        if ws.max_row > 1:
            row2 = [ws.cell(2,c).value for c in range(1, min((ws.max_column or 0)+1, 6))]
            print(f'  Row2 sample: {row2}')
"


Roadmap: 186 rows x 15 cols
  Headers: ['RowNo', 'OriginalID', 'DependencyOrder', 'ClusterNo', 'Cluster', 'Item', 'Type', 'Action', 'Priority', 'Context', 'LikelyMathOrFormula', 'ProofOrValidationSketch', 'Dependencies', 'SourceBasis', 'SequenceCheck']
  Row2 sample: [1, 121, '0.1', 0, 'Claim discipline and terminology guardrails']
Summary: 34 rows x 8 cols
  Headers: ['Cubie Theorem / Rewrite Roadmap � QA Summary', None, None, None, None, None, None, None]
  Row2 sample: [None, None, None, None, None]
Legend: 8 rows x 2 cols
  Headers: ['Column', 'Meaning']
  Row2 sample: ['RowNo', 'Sequential row number in dependency order. Should be 1 through 185 with no gaps.']
Sources: 7 rows x 2 cols
  Headers: ['Source Basis', 'How used in roadmap']
  Row2 sample: ['Conversation synthesis', 'Primary source for the full theorem/rewrite backlog and dependency order.']


Now I have everything I need. Writing the loader script:


Write

#!/usr/bin/env python3
"""
load_jsonl_to_excel.py
Load cubie_full_proof_stack.jsonl into cubie_theorem_roadmap_full.xlsx.

Adds sheets:
  ProofStack     — all 1,298 records (master view)
  MasterTheorems — 716 FORMAL rows with Coq+Lean code
  VerusProofs    — 251 VERUS rows
  Predicates     — 128 PREDICATE_SCAFFOLD rows
  RoadmapObligs  — 203 ROADMAP obligation rows

Existing sheets (Roadmap, Summary, Legend, Sources) are preserved.
Output: Downloads/cubie_master_proof_stack.xlsx
"""

import json
import openpyxl
from openpyxl.styles import (
    Font, PatternFill, Alignment, Border, Side
)
from openpyxl.utils import get_column_letter
from pathlib import Path

REPO      = Path(__file__).parent.parent
JSONL     = REPO / "roadmap" / "cubie_full_proof_stack.jsonl"
SRC_XLSX  = Path("C:/Users/NickV/Downloads/cubie_theorem_roadmap_full.xlsx")
OUT_XLSX  = Path("C:/Users/NickV/Downloads/cubie_master_proof_stack.xlsx")

# ---------------------------------------------------------------------------
# Colours per source
# ---------------------------------------------------------------------------
COLORS = {
    "FORMAL":             "DDEEFF",   # blue-grey
    "VERUS":              "DFFFD6",   # green
    "PREDICATE_SCAFFOLD": "FFF8DC",   # cream
    "ROADMAP":            "F5E6FF",   # lavender
}
HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
HEADER_FONT = Font(bold=True, color="FFFFFF", size=10)
BODY_FONT   = Font(size=9)
WRAP_ALIGN  = Alignment(wrap_text=True, vertical="top")
TOP_ALIGN   = Alignment(vertical="top")

def header_style(cell):
    cell.fill = HEADER_FILL
    cell.font = HEADER_FONT
    cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)

def body_style(cell, source=""):
    color = COLORS.get(source, "FFFFFF")
    cell.fill = PatternFill("solid", fgColor=color)
    cell.font  = BODY_FONT
    is_code = isinstance(cell.value, str) and ("\n" in (cell.value or ""))
    cell.alignment = WRAP_ALIGN if is_code else TOP_ALIGN

# ---------------------------------------------------------------------------
# Column definitions for the ProofStack sheet
# ---------------------------------------------------------------------------
COLUMNS = [
    ("seq",             "ID",                    14),
    ("source",          "Source",                14),
    ("module",          "Module",                28),
    ("theorem_name",    "Theorem / Fn Name",     32),
    ("kind",            "Kind",                  14),
    ("cluster_no",      "Cluster #",              9),
    ("cluster",         "Cluster",               30),
    ("deliverable",     "Deliverable",           18),
    ("version_chain",   "Version Chain",         16),
    ("formal_systems",  "Formal Systems",        16),
    ("status",          "Status",                18),
    ("axiom_profile",   "Axiom Profile",         18),
    ("coq_file",        "Coq File",              28),
    ("lean_file",       "Lean File",             28),
    ("verus_file",      "Verus File",            26),
    ("coq_line",        "Coq Line",               9),
    ("coq_sha256",      "Coq SHA256",            20),
    ("lean_sha256",     "Lean SHA256",           20),
    ("verus_status",    "Verus Status",          14),
    ("canonical",       "Canonical",             10),
    ("coq_code",        "Coq Code",              50),
    ("lean_code",       "Lean Code",             50),
    ("verus_code",      "Verus Code",            50),
    ("predicate_math",  "Math / Formula",        40),
    ("predicate_llm",   "LLM Context",           40),
    ("predicate_human", "Human Description",     36),
    ("notes",           "Notes",                 36),
]

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def load_jsonl():
    rows = []
    with open(JSONL, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows

def write_sheet(ws, rows, columns, freeze="B2", max_row_height=120):
    """Write a list-of-dict rows to worksheet using column spec."""
    # Headers
    for col_idx, (key, label, width) in enumerate(columns, 1):
        cell = ws.cell(row=1, column=col_idx, value=label)
        header_style(cell)
        ws.column_dimensions[get_column_letter(col_idx)].width = width

    ws.row_dimensions[1].height = 28

    # Data
    for row_idx, rec in enumerate(rows, 2):
        source = rec.get("source", "")
        for col_idx, (key, label, width) in enumerate(columns, 1):
            val = rec.get(key, "")
            if val is None:
                val = ""
            # Truncate very long code cells for Excel performance
            if isinstance(val, str) and len(val) > 3200:
                val = val[:3200] + "\n… (truncated)"
            cell = ws.cell(row=row_idx, column=col_idx, value=val)
            body_style(cell, source)

        # Row height: taller for rows with code
        has_code = any(rec.get(k, "") for k in ("coq_code","lean_code","verus_code"))
        ws.row_dimensions[row_idx].height = 60 if has_code else 18

    # Freeze
    ws.freeze_panes = freeze
    ws.auto_filter.ref = ws.dimensions

def write_filtered_sheet(ws, all_rows, source_filter, columns, freeze="B2"):
    rows = [r for r in all_rows if r.get("source") == source_filter]
    write_sheet(ws, rows, columns, freeze=freeze)
    return len(rows)

# ---------------------------------------------------------------------------
# Master theorem sheet — trimmed columns (no predicate fields)
# ---------------------------------------------------------------------------
FORMAL_COLS = [c for c in COLUMNS if c[0] not in
               ("predicate_math","predicate_llm","predicate_human")]

VERUS_COLS = [
    ("seq",           "ID",             18),
    ("module",        "Module",         26),
    ("theorem_name",  "Fn Name",        32),
    ("cluster_no",    "Cluster #",       9),
    ("cluster",       "Cluster",        30),
    ("status",        "Status",         16),
    ("verus_file",    "Verus File",     26),
    ("verus_code",    "Verus Code",     70),
    ("notes",         "Notes",          30),
]

PRED_COLS = [
    ("seq",              "ID",                 10),
    ("module",           "Source",             20),
    ("predicate_math",   "Math / LaTeX",       50),
    ("predicate_llm",    "LLM Context",        50),
    ("predicate_human",  "Human Description",  50),
]

RDM_COLS = [
    ("seq",             "ID",                 10),
    ("theorem_name",    "Formal Name",        38),
    ("kind",            "Type",               10),
    ("cluster_no",      "Cluster #",           9),
    ("cluster",         "Cluster",            30),
    ("status",          "Status",             24),
    ("coq_code",        "Coq Code",           50),
    ("lean_code",       "Lean4 Code",         50),
    ("verus_code",      "Verus Code",         50),
    ("predicate_math",  "Math / Formula",     40),
    ("predicate_human", "Title",              30),
    ("notes",           "Scope Note",         36),
]

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    print(f"Loading JSONL ({JSONL.name})...")
    all_rows = load_jsonl()
    print(f"  {len(all_rows):,} records loaded")

    print(f"Opening source workbook ({SRC_XLSX.name})...")
    wb = openpyxl.load_workbook(SRC_XLSX)

    # Remove existing sheets we are about to replace
    for name in ["ProofStack","MasterTheorems","VerusProofs","Predicates","RoadmapObligs"]:
        if name in wb.sheetnames:
            del wb[name]

    # ---- ProofStack (all 1,298) ----
    print("Writing ProofStack sheet (all records)...")
    ws_all = wb.create_sheet("ProofStack")
    write_sheet(ws_all, all_rows, COLUMNS)
    ws_all.sheet_properties.tabColor = "1F4E79"

    # ---- MasterTheorems (716 FORMAL) ----
    print("Writing MasterTheorems sheet...")
    ws_formal = wb.create_sheet("MasterTheorems")
    n = write_filtered_sheet(ws_formal, all_rows, "FORMAL", FORMAL_COLS)
    ws_formal.sheet_properties.tabColor = "2E75B6"
    print(f"  {n} rows")

    # ---- VerusProofs (251) ----
    print("Writing VerusProofs sheet...")
    ws_verus = wb.create_sheet("VerusProofs")
    n = write_filtered_sheet(ws_verus, all_rows, "VERUS", VERUS_COLS)
    ws_verus.sheet_properties.tabColor = "375623"
    print(f"  {n} rows")

    # ---- Predicates (128) ----
    print("Writing Predicates sheet...")
    ws_pred = wb.create_sheet("Predicates")
    n = write_filtered_sheet(ws_pred, all_rows, "PREDICATE_SCAFFOLD", PRED_COLS)
    ws_pred.sheet_properties.tabColor = "C6A800"
    print(f"  {n} rows")

    # ---- RoadmapObligs (203) ----
    print("Writing RoadmapObligs sheet...")
    ws_rdm = wb.create_sheet("RoadmapObligs")
    n = write_filtered_sheet(ws_rdm, all_rows, "ROADMAP", RDM_COLS)
    ws_rdm.sheet_properties.tabColor = "7030A0"
    print(f"  {n} rows")

    # Reorder: put new sheets first
    order = ["ProofStack","MasterTheorems","VerusProofs","Predicates","RoadmapObligs",
             "Roadmap","Summary","Legend","Sources"]
    for i, name in enumerate(order):
        if name in wb.sheetnames:
            wb.move_sheet(name, offset=wb.sheetnames.index(name) - i)

    print(f"\nSaving → {OUT_XLSX}")
    wb.save(OUT_XLSX)
    size_mb = OUT_XLSX.stat().st_size / (1024*1024)
    print(f"Done. {size_mb:.1f} MB")

if __name__ == "__main__":
    main()