vex-core 1.7.0

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

use crate::merkle::Hash;
use crate::zk::{ZkError, ZkVerifier};
use serde::{Deserialize, Serialize};
use sha2::Digest;
use utoipa::ToSchema;

/// Intent Data (VEX Pillar)
/// Proves the proposed action before execution. It supports two variants:
/// - Transparent: Standard human-readable reasoning (Standard).
/// - Shadow: STARK-proofed hidden intent for privacy (High-Compliance).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
#[serde(untagged, rename_all = "snake_case")]
pub enum IntentData {
    Transparent {
        request_sha256: String,
        confidence: f64,
        #[serde(default)]
        capabilities: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        magpie_source: Option<String>,

        /// Phase 6: Continuation authorization
        #[serde(skip_serializing_if = "Option::is_none")]
        continuation_token: Option<ContinuationToken>,

        /// Catch-all for extra fields to preserve binary parity in JCS.
        #[serde(flatten, default)]
        #[schema(ignore)]
        metadata: SchemaValue,
    },
    Shadow {
        commitment_hash: String,
        stark_proof_b64: String,
        #[schema(ignore)]
        public_inputs: SchemaValue,

        /// New Phase 2: Plonky3 Circuit Identity
        #[serde(skip_serializing_if = "Option::is_none")]
        circuit_id: Option<String>,

        /// Phase 6: Continuation authorization
        #[serde(skip_serializing_if = "Option::is_none")]
        continuation_token: Option<ContinuationToken>,

        /// Catch-all for extra fields to preserve binary parity in JCS.
        #[serde(flatten, default)]
        #[schema(ignore)]
        metadata: SchemaValue,
    },
}

impl IntentData {
    pub fn continuation_token(&self) -> Option<&ContinuationToken> {
        match self {
            IntentData::Transparent {
                continuation_token, ..
            } => continuation_token.as_ref(),
            IntentData::Shadow {
                continuation_token, ..
            } => continuation_token.as_ref(),
        }
    }

    pub fn circuit_id(&self) -> Option<String> {
        match self {
            IntentData::Transparent { .. } => None,
            IntentData::Shadow { circuit_id, .. } => circuit_id.clone(),
        }
    }

    pub fn metadata(&self) -> &SchemaValue {
        match self {
            IntentData::Transparent { metadata, .. } => metadata,
            IntentData::Shadow { metadata, .. } => metadata,
        }
    }
}

/// A wrapper for serde_json::Value that implements utoipa::ToSchema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(transparent)]
pub struct SchemaValue(pub serde_json::Value);

impl std::ops::Deref for SchemaValue {
    type Target = serde_json::Value;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for SchemaValue {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Default for SchemaValue {
    fn default() -> Self {
        Self(serde_json::Value::Null)
    }
}

impl SchemaValue {
    pub fn is_null(&self) -> bool {
        self.0.is_null()
    }
}

impl utoipa::PartialSchema for SchemaValue {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        utoipa::openapi::RefOr::T(utoipa::openapi::ObjectBuilder::new().into())
    }
}

impl utoipa::ToSchema for SchemaValue {
    fn name() -> std::borrow::Cow<'static, str> {
        "SchemaValue".into()
    }
}

impl IntentData {
    pub fn to_jcs_hash(&self) -> Result<Hash, String> {
        let jcs_bytes =
            serde_jcs::to_vec(self).map_err(|e| format!("JCS serialization failed: {}", e))?;
        Ok(Hash::digest(&jcs_bytes))
    }

    /// Verifies the Zero-Knowledge proof for Shadow intents.
    /// For Transparent intents, this always returns Ok(true).
    pub fn verify_shadow(&self, verifier: &dyn ZkVerifier) -> Result<bool, ZkError> {
        match self {
            IntentData::Transparent { .. } => Ok(true),
            IntentData::Shadow {
                commitment_hash,
                stark_proof_b64,
                public_inputs,
                ..
            } => verifier.verify_stark(commitment_hash, stark_proof_b64, &public_inputs.0),
        }
    }

    /// Accesses the typed ShadowPublicInputs for a Shadow intent.
    pub fn shadow_public_inputs(&self) -> Result<ShadowPublicInputs, ZkError> {
        match self {
            IntentData::Shadow { public_inputs, .. } => {
                ShadowPublicInputs::from_schema_value(public_inputs).map_err(ZkError::ConfigError)
            }
            _ => Err(ZkError::ConfigError("Not a Shadow intent".to_string())),
        }
    }
}

/// Typed Public Inputs for Shadow Intents (Phase 2 Hardening)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct ShadowPublicInputs {
    pub schema: String,
    pub start_root: String,
    pub commitment_hash: String,
    pub circuit_id: String,
    /// The salt used in the semantic commitment (Phase 3 Binding)
    pub public_salt: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verifier_params_hash: Option<String>,
}

impl ShadowPublicInputs {
    pub const SCHEMA_V1: &'static str = "vex.shadow_intent.public_inputs.v1";

    pub fn validate(&self) -> Result<(), String> {
        if self.schema != Self::SCHEMA_V1 {
            return Err("unsupported schema".to_string());
        }
        if self.start_root.len() != 64 || !self.start_root.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err("start_root must be 32-byte hex".to_string());
        }
        if self.commitment_hash.len() != 64
            || !self.commitment_hash.chars().all(|c| c.is_ascii_hexdigit())
        {
            return Err("commitment_hash must be 32-byte hex".to_string());
        }
        if self.circuit_id.trim().is_empty() {
            return Err("circuit_id must not be empty".to_string());
        }
        Ok(())
    }

    pub fn to_schema_value(&self) -> SchemaValue {
        SchemaValue(serde_json::to_value(self).expect("serializes"))
    }

    pub fn from_schema_value(v: &SchemaValue) -> Result<Self, String> {
        let decoded: Self = serde_json::from_value(v.0.clone()).map_err(|e| e.to_string())?;
        decoded.validate()?;
        Ok(decoded)
    }

    /// Verifies that the commitment hash matches the provided prompt and salt.
    /// This is the "Commitment Opening" step for auditors (Phase 5).
    pub fn verify_opening(&self, prompt: &str) -> bool {
        let salt = hex::decode(&self.public_salt).unwrap_or_default();
        let expected = semantic_commitment_hash(prompt, &salt);
        self.commitment_hash == expected
    }
}

pub const SHADOW_INTENT_DOMAIN_TAG: &[u8] = b"vex.shadow_intent.commitment.v1";

pub const FULL_ROUNDS_START: usize = 4;
pub const PARTIAL_ROUNDS: usize = 22;
pub const TOTAL_ROUNDS: usize = 30;
pub const WIDTH: usize = 8;
pub const FULL_WIDTH: usize = 28;

pub const GOLDILOCKS_PRIME: u64 = 0xFFFF_FFFF_0000_0001;

pub const COL_STATE_START: usize = 0;
pub const COL_AUX_START: usize = 8;
pub const COL_CONST_START: usize = 16;
pub const COL_IS_FULL: usize = 24;
pub const COL_IS_ACTIVE: usize = 25;
pub const COL_IS_LAST: usize = 26;
pub const COL_IS_REAL: usize = 27;

pub const ME_CIRC: [u64; 8] = [3, 1, 1, 1, 1, 1, 1, 2];
pub const MU: [u64; 4] = [5, 6, 5, 6];

pub fn get_round_constant(round: usize, element: usize) -> u64 {
    let base = (round + 1) as u64 * 0x12345678;
    let offset = (element + 1) as u64 * 0x87654321;
    base.wrapping_add(offset) % GOLDILOCKS_PRIME
}

/// Computes the structural permutation of a state (reference implementation).
pub fn structural_permute(state: &mut [u64; 8]) {
    use p3_field::PrimeField64;
    use p3_goldilocks::Goldilocks;

    let mut g_state = [Goldilocks::default(); 8];
    for i in 0..8 {
        g_state[i] = Goldilocks::new(state[i] % GOLDILOCKS_PRIME);
    }

    for step in 0..TOTAL_ROUNDS {
        let is_full = !(FULL_ROUNDS_START..FULL_ROUNDS_START + PARTIAL_ROUNDS).contains(&step);
        let mut sbox_out = [Goldilocks::default(); 8];
        for i in 0..8 {
            let x = g_state[i];
            sbox_out[i] = if is_full || i == 0 {
                let x2 = x * x;
                let x4 = x2 * x2;
                x4 * x2 * x
            } else {
                x
            };
        }

        let mut next_state = [Goldilocks::default(); 8];
        if is_full {
            for r in 0..8 {
                let mut sum = Goldilocks::default();
                for c in 0..8 {
                    sum += Goldilocks::new(ME_CIRC[(8 + r - c) % 8]) * sbox_out[c];
                }
                next_state[r] = sum + Goldilocks::new(get_round_constant(step, r));
            }
        } else {
            let mut sum_sbox = Goldilocks::default();
            for x in sbox_out.iter() {
                sum_sbox += *x;
            }
            for i in 0..8 {
                let mu_m1 = MU[i % 4] - 1;
                next_state[i] = Goldilocks::new(mu_m1) * sbox_out[i]
                    + sum_sbox
                    + Goldilocks::new(get_round_constant(step, i));
            }
        }
        g_state = next_state;
    }

    for i in 0..8 {
        state[i] = PrimeField64::as_canonical_u64(&g_state[i]);
    }
}

/// Computes a canonical, length-prefixed encoding for ZK commitment preimages.
/// Format: [DOMAIN_TAG] [PROMPT_LEN:4] [PROMPT] [SALT_LEN:4] [SALT]
pub fn canonical_encode_shadow_intent(prompt: &str, salt: &[u8]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(
        SHADOW_INTENT_DOMAIN_TAG.len() + std::mem::size_of::<u64>() * 2 + prompt.len() + salt.len(),
    );

    bytes.extend_from_slice(SHADOW_INTENT_DOMAIN_TAG);
    bytes.extend_from_slice(&(prompt.len() as u64).to_le_bytes());
    bytes.extend_from_slice(prompt.as_bytes());
    bytes.extend_from_slice(&(salt.len() as u64).to_le_bytes());
    bytes.extend_from_slice(salt);
    bytes
}

/// Computes the semantic commitment hash for a shadow intent.
/// Currently uses the structural permutation for ZK consistency.
pub fn semantic_commitment_hash(prompt: &str, salt: &[u8]) -> String {
    let preimage = sha2::Sha256::digest(canonical_encode_shadow_intent(prompt, salt));

    // Phase 3A: 64-bit binding. We use only the first 8 bytes as Lane 0.
    // In Phase 3B/4, we will absorb the full 256 bits into state[0..4].
    let initial_val = u64::from_le_bytes(preimage[0..8].try_into().unwrap());

    let mut state = [0u64; 8];
    state[0] = initial_val;

    structural_permute(&mut state);

    // Bind to the first 4 lanes (32 bytes / 256 bits)
    let mut hash_bytes = Vec::with_capacity(32);
    for lane in state.iter().take(4) {
        hash_bytes.extend_from_slice(&lane.to_le_bytes());
    }
    hex::encode(hash_bytes)
}

/// Phase 4A: Canonical M31 Chunking Specification.
/// Maps a 256-bit hash (32 bytes-LE) into 9 M31 field elements using the LE rule:
/// chunk_i = (H >> (31 * i)) & ((1 << 31) - 1)
/// This ensures injective and bit-exact binding for Circle STARKs.
pub fn hash_to_m31_chunks(hash: &[u8; 32]) -> [u32; 9] {
    let mut chunks = [0u32; 9];

    // Convert the 32-byte hash to a bit-stream for exact 31-bit windowing.
    // Index 8 (the 9th chunk) will contain the remaining 8 bits.
    for (i, item) in chunks.iter_mut().enumerate() {
        let bit_offset = i * 31;
        let mut val = 0u64;

        for b in 0..31 {
            let total_bit = bit_offset + b;
            if total_bit >= 256 {
                break;
            }

            let byte_idx = total_bit / 8;
            let bit_in_byte = total_bit % 8;

            if (hash[byte_idx] & (1 << bit_in_byte)) != 0 {
                val |= 1 << b;
            }
        }
        *item = (val & 0x7FFFFFFF) as u32;
    }
    chunks
}

/// Authority Data (CHORA Pillar)
/// Proves the governance decision.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct AuthorityData {
    pub capsule_id: String,
    pub outcome: String,
    pub reason_code: String,
    pub trace_root: String,
    pub nonce: String,

    /// New Phase 2: CHORA Binding Mode Fields
    #[serde(skip_serializing_if = "Option::is_none")]
    pub escalation_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub binding_status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub continuation_token: Option<ContinuationToken>,

    /// Decision classification for deterministic precedence (STRUCTURAL / POLICY / AMBIGUITY / ALLOW)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_class: Option<String>,

    #[serde(
        default = "default_sensor_value",
        skip_serializing_if = "SchemaValue::is_null"
    )]
    pub gate_sensors: SchemaValue,

    /// Catch-all for extra fields to preserve binary parity in JCS.
    #[serde(flatten, default)]
    pub metadata: SchemaValue,
}

impl AuthorityData {
    pub const CLASS_STRUCTURAL: &'static str = "STRUCTURAL_TERMINAL";
    pub const CLASS_POLICY: &'static str = "POLICY_TERMINAL";
    pub const CLASS_AMBIGUITY: &'static str = "ESCALATABLE_AMBIGUITY";
    pub const CLASS_ALLOW: &'static str = "ALLOW_PATH";
}

fn default_sensor_value() -> SchemaValue {
    SchemaValue(serde_json::Value::Null)
}

/// Witness Data (CHORA Append-Only Log)
/// Proves the receipt issuance parameters.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct WitnessData {
    pub chora_node_id: String,
    pub receipt_hash: String,
    pub timestamp: u64,
    /// Diagnostic or display-only fields that are NOT part of the commitment surface.
    #[serde(flatten, default)]
    pub metadata: SchemaValue,
}

impl WitnessData {
    /// Compute the "witness_hash" using the v0.3 Minimal Witness spec.
    /// ONLY chora_node_id and timestamp are committed.
    /// receipt_hash is post-seal metadata and is NOT part of the witness commitment surface.
    /// Ref: CHORA_VERIFICATION_CONTRACT_v0.3.md
    pub fn to_commitment_hash(&self) -> Result<Hash, String> {
        #[derive(Serialize)]
        struct MinimalWitness<'a> {
            chora_node_id: &'a str,
            timestamp: u64,
        }

        let minimal = MinimalWitness {
            chora_node_id: &self.chora_node_id,
            timestamp: self.timestamp,
        };

        let jcs_bytes = serde_jcs::to_vec(&minimal)
            .map_err(|e| format!("JCS serialization of minimal witness failed: {}", e))?;

        Ok(Hash::digest(&jcs_bytes))
    }

    pub fn to_jcs_hash(&self) -> Result<Hash, String> {
        self.to_commitment_hash()
    }
}

/// Identity Data (Attest Pillar)
/// Proves the silicon source and its integrity state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct IdentityData {
    pub aid: String,
    pub identity_type: String,
    /// Platform Configuration Registers (PCRs) for hardware-rooted integrity.
    /// Map of PCR index (e.g., 0, 7, 11) to SHA-256 hash (hex string).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pcrs: Option<std::collections::HashMap<u32, String>>,

    /// Catch-all for extra fields to preserve binary parity in JCS.
    #[serde(flatten, default)]
    pub metadata: SchemaValue,
}

/// Continuation Token (Phase 2 Enforcement Primitive)
/// A signed artifact that permits execution after an escalation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct ContinuationToken {
    pub payload: ContinuationPayload,
    pub signature: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct ExecutionTarget {
    pub aid: String,
    pub circuit_id: String,
    pub intent_hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct ContinuationPayload {
    pub schema: String,
    pub ledger_event_id: String,
    pub source_capsule_root: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolution_event_id: Option<String>,
    #[serde(default)]
    pub capabilities: Vec<String>,
    pub nonce: String,
    pub execution_target: ExecutionTarget,
    pub iat: i64,
    pub exp: i64,
    pub issuer: String,
}

impl ContinuationPayload {
    /// Validates the token's lifecycle (iat/exp) with a grace period.
    pub fn validate_lifecycle(&self, now: chrono::DateTime<chrono::Utc>) -> Result<(), String> {
        let now_unix = now.timestamp();
        let leeway = 30; // 30 seconds

        if now_unix < self.iat - leeway {
            return Err("Token issued in the future (beyond leeway)".to_string());
        }

        if now_unix > self.exp + leeway {
            return Err("Token expired (beyond leeway)".to_string());
        }

        Ok(())
    }
}

impl ContinuationToken {
    /// Computes the JCS hash of the payload for signature verification.
    pub fn payload_hash(&self) -> Result<Vec<u8>, String> {
        let jcs_bytes = serde_jcs::to_vec(&self.payload)
            .map_err(|e| format!("JCS serialization failed: {}", e))?;
        let mut hasher = sha2::Sha256::new();
        hasher.update(&jcs_bytes);
        Ok(hasher.finalize().to_vec())
    }

    /// Verifies the v3 token signature (Ed25519 over JCS payload hash).
    pub fn verify_v3(&self, public_key_hex: &str) -> Result<bool, String> {
        use ed25519_dalek::{Signature, Verifier, VerifyingKey};

        let pub_key_bytes =
            hex::decode(public_key_hex).map_err(|e| format!("Invalid public key hex: {}", e))?;
        let public_key = VerifyingKey::from_bytes(
            pub_key_bytes
                .as_slice()
                .try_into()
                .map_err(|_| "Invalid Key Length")?,
        )
        .map_err(|e| format!("Invalid Ed25519 public key: {}", e))?;

        let sig_bytes =
            hex::decode(&self.signature).map_err(|e| format!("Invalid signature hex: {}", e))?;

        let sig_array: [u8; 64] = sig_bytes
            .as_slice()
            .try_into()
            .map_err(|_| "Signature must be 64 bytes".to_string())?;
        let signature = Signature::from_bytes(&sig_array);

        let hash = self.payload_hash()?;

        Ok(public_key.verify(&hash, &signature).is_ok())
    }
}

/// Crypto verification details.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct CryptoData {
    pub algo: String,
    pub public_key_endpoint: String,
    pub signature_scope: String,
    pub signature_b64: String,
}

/// Auditability metadata to link the raw payload to the intent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct RequestCommitment {
    pub canonicalization: String,
    pub payload_sha256: String,
    pub payload_encoding: String,
}

/// A Composite Evidence Capsule (The v0.1.0 "Zero-Trust Singularity" Root)
/// Binds Intent, Authority, Identity, and Witness into a single commitment.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct Capsule {
    pub capsule_id: String,
    /// VEX Pillar: What was intended
    pub intent: IntentData,
    /// CHORA Pillar: Who authorized it
    pub authority: AuthorityData,
    /// ATTEST Pillar: Where it executed (Silicon)
    pub identity: IdentityData,
    /// CHORA Log Pillar: Where the receipt lives
    pub witness: WitnessData,

    // Derived hashes for transparency
    pub intent_hash: String,
    pub authority_hash: String,
    pub identity_hash: String,
    pub witness_hash: String,
    pub capsule_root: String,

    /// Ed25519 signature details
    pub crypto: CryptoData,

    /// Optional auditable link to raw payload (v0.2+)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_commitment: Option<RequestCommitment>,
}

impl Capsule {
    /// Compute the canonical "capsule_root" using the Binary Merkle Tree model.
    /// This enables ZK-Explorer partial disclosure proofs for "Shadow Intents".
    pub fn to_composite_hash(&self) -> Result<Hash, String> {
        let intent_h = self.intent.to_jcs_hash()?;

        // Authority and Identity are hashed as "Naked" leaves for byte-level interop with CHORA.
        let authority_h = {
            let jcs = serde_jcs::to_vec(&self.authority).map_err(|e| e.to_string())?;
            Hash::digest(&jcs)
        };

        let identity_h = {
            let jcs = serde_jcs::to_vec(&self.identity).map_err(|e| e.to_string())?;
            Hash::digest(&jcs)
        };

        let witness_h = self.witness.to_jcs_hash()?;

        // Build 4-leaf Merkle Tree (RFC 6962 compatible structure)
        let leaves = vec![
            ("intent".to_string(), intent_h),
            ("authority".to_string(), authority_h),
            ("identity".to_string(), identity_h),
            ("witness".to_string(), witness_h),
        ];

        let tree = crate::merkle::MerkleTree::from_leaves(leaves);

        tree.root_hash()
            .cloned()
            .ok_or_else(|| "Failed to calculate Merkle root".to_string())
    }
}

/// A Spec-Grade Receipt (Phase 6 Hardening)
/// Binds a validated Evidence Capsule to its proving context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct VexReceipt {
    pub schema: String,
    pub capsule: Capsule,
    pub proving_metadata: ProvingMetadata,
}

impl VexReceipt {
    pub const SCHEMA_V1: &'static str = "vex.receipt.v1";

    pub fn new(capsule: Capsule, proving_metadata: ProvingMetadata) -> Self {
        Self {
            schema: Self::SCHEMA_V1.to_string(),
            capsule,
            proving_metadata,
        }
    }
}

/// Metadata describing the Zero-Knowledge proving process.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct ProvingMetadata {
    pub circuit_id: String,
    pub proving_engine: String,
    pub machine_id: String,
    pub proving_duration_ms: u64,
    pub timestamp: u64,
}

/// An Aggregate Proof for a sequence of authorized transitions.
/// Used to prove the final state of a multi-step governed stream.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct StreamFinalProof {
    pub stream_id: String,
    pub receipts: Vec<VexReceipt>,
    pub aggregate_proof_b64: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_intent_segment_jcs_deterministic() {
        let segment1 = IntentData::Transparent {
            request_sha256: "8ee6010d905547c377c67e63559e989b8073b168f11a1ffefd092c7ca962076e"
                .to_string(),
            confidence: 0.95,
            capabilities: vec![],
            magpie_source: None,
            continuation_token: None,
            metadata: SchemaValue::default(),
        };
        let segment2 = segment1.clone();

        let hash1 = segment1.to_jcs_hash().unwrap();
        let hash2 = segment2.to_jcs_hash().unwrap();

        assert_eq!(hash1, hash2, "JCS hashing must be deterministic");
    }

    #[test]
    fn test_intent_segment_content_change() {
        let segment1 = IntentData::Transparent {
            request_sha256: "a".into(),
            confidence: 0.5,
            capabilities: vec![],
            magpie_source: None,
            continuation_token: None,
            metadata: SchemaValue::default(),
        };
        let mut segment2 = segment1.clone();
        if let IntentData::Transparent {
            ref mut confidence, ..
        } = segment2
        {
            *confidence = 0.9;
        }

        let hash1 = segment1.to_jcs_hash().unwrap();
        let hash2 = segment2.to_jcs_hash().unwrap();

        assert_ne!(hash1, hash2, "Hashes must change when content changes");
    }

    #[test]
    fn test_shadow_intent_jcs_deterministic() {
        let segment1 = IntentData::Shadow {
            commitment_hash: "5555555555555555555555555555555555555555555555555555555555555555"
                .to_string(),
            stark_proof_b64: "c29tZS1zdGFyay1wcm9vZg==".to_string(),
            public_inputs: SchemaValue(serde_json::json!({
                "policy_id": "standard-v1",
                "outcome_commitment": "ALLOW"
            })),
            circuit_id: None,
            continuation_token: None,
            metadata: SchemaValue::default(),
        };
        let segment2 = segment1.clone();

        let hash1 = segment1.to_jcs_hash().unwrap();
        let hash2 = segment2.to_jcs_hash().unwrap();

        assert_eq!(hash1, hash2, "Shadow JCS hashing must be deterministic");

        // Verify JCS serialization (untagged)
        let jcs_bytes = serde_jcs::to_vec(&segment1).unwrap();
        let jcs_str = String::from_utf8(jcs_bytes).unwrap();
        assert!(
            jcs_str.contains("\"commitment_hash\""),
            "JCS must include the commitment_hash"
        );
    }

    #[test]
    fn test_witness_metadata_exclusion() {
        let base_witness = WitnessData {
            chora_node_id: "node-1".to_string(),
            receipt_hash: "hash-1".to_string(),
            timestamp: 1710396000,
            metadata: SchemaValue(serde_json::Value::Null),
        };

        let hash_base = base_witness.to_commitment_hash().unwrap();

        let mut metadata_witness = base_witness.clone();
        metadata_witness.metadata = SchemaValue(serde_json::json!({
            "witness_mode": "sentinel",
            "diagnostics": {
                "latency_ms": 42
            }
        }));

        let hash_with_metadata = metadata_witness.to_commitment_hash().unwrap();

        assert_eq!(
            hash_base, hash_with_metadata,
            "Witness hash must be invariant to extra metadata fields"
        );
    }

    #[test]
    fn test_witness_segment_minimal_interop() {
        // v0.3 spec: witness commitment = {chora_node_id, timestamp} ONLY.
        // receipt_hash is post-seal metadata and is excluded.
        // Canonical JCS surface: {"chora_node_id":"chora-gate-v1","timestamp":1710396000}
        let witness = WitnessData {
            chora_node_id: "chora-gate-v1".to_string(),
            receipt_hash: "ignored-in-v03".to_string(),
            timestamp: 1710396000,
            metadata: SchemaValue(serde_json::json!({
                "witness_mode": "full",
                "observational_only": false
            })),
        };

        let hash_hex = witness.to_commitment_hash().expect("Hashing failed");

        // SHA256(0x00 + {"chora_node_id":"chora-gate-v1","timestamp":1710396000})
        assert_eq!(
            hash_hex.to_hex(),
            "87657d67389ca1a0e3e9bd4bccb5ab60a1cdcc59902d4cd67826d285dd98bff5",
            "v0.3 witness hash must include 0x00 leaf prefix and exclude receipt_hash"
        );
    }

    #[test]
    fn test_authority_extra_fields_parity() {
        // Specimen based on the CHORA example
        let json_data = serde_json::json!({
            "capsule_id": "example-capsule-001",
            "outcome": "ALLOW",
            "reason_code": "policy_ok",
            "trace_root": "trace-001",
            "nonce": "1234567890",
            "gate_sensors": null,
            "rule_set_owner": "chora-authority-node",
            "fail_closed": true
        });

        let authority: AuthorityData = serde_json::from_value(json_data.clone()).unwrap();

        // Ensure extra fields went into metadata
        assert_eq!(authority.metadata["rule_set_owner"], "chora-authority-node");
        assert_eq!(authority.metadata["fail_closed"], true);

        // Verify JCS serialization includes the extra fields
        let jcs_bytes = serde_jcs::to_vec(&authority).unwrap();
        let jcs_str = String::from_utf8(jcs_bytes).unwrap();
        assert!(jcs_str.contains("\"rule_set_owner\":\"chora-authority-node\""));
    }
}