exochain-sdk 0.2.0-beta

EXOCHAIN SDK — ergonomic Rust API for the constitutional governance fabric
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Constitutional Governance Runtime (CGR) Kernel interface.
//!
//! The **CGR kernel** is the heart of EXOCHAIN. Every action that matters —
//! reading data, delegating authority, invoking a tool — is first submitted
//! to the kernel, which checks the action against the constitution and the
//! eight structural invariants (including `NoSelfGrant`, `ConsentRequired`,
//! and `KernelImmutability`). Only if the kernel returns `Permitted` does the
//! action run.
//!
//! [`ConstitutionalKernel`] is a simplified, ergonomic wrapper around
//! [`exo_gatekeeper::Kernel`]. It initialises the kernel with the default
//! EXOCHAIN constitution text and the full set of eight constitutional
//! invariants. Adjudication requires caller-supplied authority signing material
//! so the SDK never fabricates a trust root.
//!
//! ## Why use this module
//!
//! - You want to ask "is this action permitted?" without having to construct
//!   the full [`exo_gatekeeper::AdjudicationContext`] by hand.
//! - You want to exercise specific invariants (self-grant, kernel
//!   modification, consent-required) in tests via the named `adjudicate_*`
//!   helpers.
//! - You want the same verdict enum to flow through your application and
//!   your test vectors.
//!
//! ## Quick start
//!
//! ```
//! use exochain_sdk::kernel::ConstitutionalKernel;
//! use exo_core::Did;
//!
//! let authority = exochain_sdk::identity::Identity::generate("authority");
//! let kernel = ConstitutionalKernel::with_authority_identity(authority);
//! let actor = Did::new("did:exo:alice").expect("valid");
//! let verdict = kernel.adjudicate(&actor, "data:medical:read");
//! assert!(verdict.is_permitted());
//! ```

use std::sync::Arc;

use exo_core::{Did, Hash256, PublicKey, Signature};
use exo_gatekeeper::{
    ActionRequest, AdjudicationContext, InvariantSet, Kernel, Verdict,
    authority_link_signature_message, provenance_signature_message,
    types::{
        AuthorityChain, AuthorityLink, BailmentState, ConsentRecord, GovernmentBranch, Permission,
        PermissionSet, Provenance, Role, TrustedAuthorityKeys, TrustedProvenanceKeys,
    },
};
use serde::{Deserialize, Serialize};

/// The default constitution bytes used by [`ConstitutionalKernel::new`].
const DEFAULT_CONSTITUTION: &[u8] = b"EXOCHAIN Constitution v1.0: \
    We the people of the EXOCHAIN fabric establish this constitution \
    to secure the blessings of ordered, consented, and auditable agency.";

/// Expected number of constitutional invariants enforced by the kernel.
const INVARIANT_COUNT: usize = 8;

/// Verdict returned by the SDK kernel.
///
/// This mirrors [`exo_gatekeeper::Verdict`] but flattens the violation list
/// to a simple `Vec<String>` so SDK consumers do not need to depend on the
/// full gatekeeper types.
///
/// # Examples
///
/// ```
/// use exochain_sdk::kernel::KernelVerdict;
///
/// let ok = KernelVerdict::Permitted;
/// assert!(ok.is_permitted());
///
/// let denied = KernelVerdict::Denied { violations: vec!["NoSelfGrant".into()] };
/// assert!(denied.is_denied());
///
/// let escalated = KernelVerdict::Escalated { reason: "human review".into() };
/// assert!(escalated.is_escalated());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum KernelVerdict {
    /// The action is permitted.
    Permitted,
    /// The action is denied — one or more invariants were violated.
    Denied {
        /// Human-readable descriptions of the violated invariants.
        violations: Vec<String>,
    },
    /// The action has been escalated for review.
    Escalated {
        /// Human-readable reason for escalation.
        reason: String,
    },
}

impl KernelVerdict {
    /// Returns `true` if the verdict is [`KernelVerdict::Permitted`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::KernelVerdict;
    /// assert!(KernelVerdict::Permitted.is_permitted());
    /// assert!(!KernelVerdict::Denied { violations: vec![] }.is_permitted());
    /// ```
    #[must_use]
    pub fn is_permitted(&self) -> bool {
        matches!(self, Self::Permitted)
    }

    /// Returns `true` if the verdict is [`KernelVerdict::Denied`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::KernelVerdict;
    /// let v = KernelVerdict::Denied { violations: vec!["NoSelfGrant".into()] };
    /// assert!(v.is_denied());
    /// ```
    #[must_use]
    pub fn is_denied(&self) -> bool {
        matches!(self, Self::Denied { .. })
    }

    /// Returns `true` if the verdict is [`KernelVerdict::Escalated`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::KernelVerdict;
    /// let v = KernelVerdict::Escalated { reason: "human in the loop".into() };
    /// assert!(v.is_escalated());
    /// ```
    #[must_use]
    pub fn is_escalated(&self) -> bool {
        matches!(self, Self::Escalated { .. })
    }
}

/// An ergonomic wrapper around the CGR [`Kernel`].
///
/// Provides a minimal adjudication interface suitable for common SDK use
/// cases: a single actor performing an action, with caller-supplied authority
/// signing material, signed provenance, and an active bailment from that
/// authority. Callers needing fine-grained control over the adjudication
/// context should use [`exo_gatekeeper::Kernel`] directly.
///
/// # Examples
///
/// ```
/// use exochain_sdk::kernel::ConstitutionalKernel;
/// use exo_core::Did;
///
/// let authority = exochain_sdk::identity::Identity::generate("authority");
/// let kernel = ConstitutionalKernel::with_authority_identity(authority);
/// assert!(kernel.verify_integrity());
/// assert_eq!(kernel.invariant_count(), 8);
///
/// let actor = Did::new("did:exo:alice").expect("valid");
/// let verdict = kernel.adjudicate(&actor, "read:profile");
/// assert!(verdict.is_permitted());
/// ```
pub struct ConstitutionalKernel {
    inner: Kernel,
    constitution: Vec<u8>,
    authority: Option<KernelAuthority>,
}

type AuthoritySigner = Arc<dyn Fn(&[u8]) -> Signature + Send + Sync>;

struct KernelAuthority {
    did: Did,
    public_key: PublicKey,
    signer: AuthoritySigner,
}

impl ConstitutionalKernel {
    /// Construct a new kernel with the default constitution and all eight
    /// constitutional invariants.
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::ConstitutionalKernel;
    /// let kernel = ConstitutionalKernel::new();
    /// assert_eq!(kernel.invariant_count(), 8);
    /// assert!(kernel.verify_integrity());
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Kernel::new(DEFAULT_CONSTITUTION, InvariantSet::all()),
            constitution: DEFAULT_CONSTITUTION.to_vec(),
            authority: None,
        }
    }

    /// Construct a new kernel with an authority signing identity.
    ///
    /// This is the common SDK path: the identity's DID becomes the authority
    /// grantor and bailor for the default adjudication context, and its secret
    /// key signs the canonical authority/provenance payloads that the kernel
    /// verifies.
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::{identity::Identity, kernel::ConstitutionalKernel};
    /// let authority = Identity::generate("authority");
    /// let kernel = ConstitutionalKernel::with_authority_identity(authority);
    /// assert!(kernel.verify_integrity());
    /// ```
    #[must_use]
    pub fn with_authority_identity(authority: crate::identity::Identity) -> Self {
        let authority_did = authority.did().clone();
        let authority_public_key = *authority.public_key();
        Self::with_authority(
            authority_did,
            authority_public_key,
            Arc::new(move |message: &[u8]| authority.sign(message)),
        )
    }

    /// Construct a new kernel with caller-supplied authority signing material.
    ///
    /// The signer must produce an Ed25519 signature over the message bytes it
    /// receives. The supplied public key is embedded in the adjudication
    /// context, and the gatekeeper verifies every signature cryptographically.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::sync::Arc;
    /// # use exochain_sdk::{crypto, kernel::ConstitutionalKernel};
    /// let authority_did = crypto::Did::new("did:exo:authority").expect("valid");
    /// let (authority_public_key, authority_secret_key) = crypto::generate_keypair();
    /// let kernel = ConstitutionalKernel::with_authority(
    ///     authority_did,
    ///     authority_public_key,
    ///     Arc::new(move |message: &[u8]| crypto::sign(message, &authority_secret_key)),
    /// );
    /// assert!(kernel.verify_integrity());
    /// ```
    #[must_use]
    pub fn with_authority(
        authority_did: Did,
        authority_public_key: PublicKey,
        authority_signer: AuthoritySigner,
    ) -> Self {
        Self {
            inner: Kernel::new(DEFAULT_CONSTITUTION, InvariantSet::all()),
            constitution: DEFAULT_CONSTITUTION.to_vec(),
            authority: Some(KernelAuthority {
                did: authority_did,
                public_key: authority_public_key,
                signer: authority_signer,
            }),
        }
    }

    /// Adjudicate `action` performed by `actor` using the signed SDK context.
    ///
    /// The SDK supplies a minimal signed default context:
    /// - A single Judicial role for `actor`.
    /// - A one-link authority chain from the configured authority to `actor`
    ///   granting `read`.
    /// - An active bailment from the configured authority to `actor` scoped to
    ///   the requested permission set.
    /// - Full human-override preservation.
    /// - Signed provenance with timestamp `"sdk"`.
    ///
    /// If the kernel was created with [`Self::new`] rather than
    /// [`Self::with_authority`] or [`Self::with_authority_identity`], this
    /// method fails closed with a denied verdict.
    ///
    /// Callers needing richer context should reach for
    /// [`exo_gatekeeper::Kernel`] directly.
    ///
    /// The action is flagged as `is_self_grant = false` and
    /// `modifies_kernel = false` by default. Helpers are available for the
    /// common deny-cases used in tests: see
    /// [`Self::adjudicate_self_grant`],
    /// [`Self::adjudicate_kernel_modification`], and
    /// [`Self::adjudicate_without_bailment`].
    ///
    /// # Examples
    ///
    /// ```
    /// use exochain_sdk::kernel::ConstitutionalKernel;
    /// use exo_core::Did;
    ///
    /// let authority = exochain_sdk::identity::Identity::generate("authority");
    /// let kernel = ConstitutionalKernel::with_authority_identity(authority);
    /// let actor = Did::new("did:exo:alice").expect("valid");
    /// let verdict = kernel.adjudicate(&actor, "data:read");
    /// assert!(verdict.is_permitted());
    /// ```
    #[must_use]
    pub fn adjudicate(&self, actor: &Did, action: &str) -> KernelVerdict {
        self.adjudicate_internal(actor, action, false, false, true, true)
    }

    /// Same as [`Self::adjudicate`] but sets `is_self_grant = true` so the
    /// kernel can enforce the `NoSelfGrant` invariant.
    ///
    /// Useful for exercising the invariant in tests: a permitted verdict
    /// here would indicate a constitutional defect.
    ///
    /// # Examples
    ///
    /// ```
    /// use exochain_sdk::kernel::ConstitutionalKernel;
    /// use exo_core::Did;
    ///
    /// let authority = exochain_sdk::identity::Identity::generate("authority");
    /// let kernel = ConstitutionalKernel::with_authority_identity(authority);
    /// let actor = Did::new("did:exo:self-granter").expect("valid");
    /// let verdict = kernel.adjudicate_self_grant(&actor, "escalate-self");
    /// assert!(verdict.is_denied());
    /// ```
    #[must_use]
    pub fn adjudicate_self_grant(&self, actor: &Did, action: &str) -> KernelVerdict {
        self.adjudicate_internal(actor, action, true, false, true, true)
    }

    /// Same as [`Self::adjudicate`] but sets `modifies_kernel = true` so the
    /// kernel can enforce the `KernelImmutability` invariant.
    ///
    /// # Examples
    ///
    /// ```
    /// use exochain_sdk::kernel::ConstitutionalKernel;
    /// use exo_core::Did;
    ///
    /// let authority = exochain_sdk::identity::Identity::generate("authority");
    /// let kernel = ConstitutionalKernel::with_authority_identity(authority);
    /// let actor = Did::new("did:exo:patcher").expect("valid");
    /// let verdict = kernel.adjudicate_kernel_modification(&actor, "patch-kernel");
    /// assert!(verdict.is_denied());
    /// ```
    #[must_use]
    pub fn adjudicate_kernel_modification(&self, actor: &Did, action: &str) -> KernelVerdict {
        self.adjudicate_internal(actor, action, false, true, true, true)
    }

    /// Same as [`Self::adjudicate`] but omits the default bailment so the
    /// kernel can enforce the `ConsentRequired` invariant.
    ///
    /// # Examples
    ///
    /// ```
    /// use exochain_sdk::kernel::ConstitutionalKernel;
    /// use exo_core::Did;
    ///
    /// let authority = exochain_sdk::identity::Identity::generate("authority");
    /// let kernel = ConstitutionalKernel::with_authority_identity(authority);
    /// let actor = Did::new("did:exo:unauth").expect("valid");
    /// let verdict = kernel.adjudicate_without_bailment(&actor, "read-data");
    /// assert!(verdict.is_denied());
    /// ```
    #[must_use]
    pub fn adjudicate_without_bailment(&self, actor: &Did, action: &str) -> KernelVerdict {
        self.adjudicate_internal(actor, action, false, false, false, true)
    }

    /// Verify that the kernel's stored constitution hash matches the
    /// configured constitution text.
    ///
    /// Returns `false` if the constitution in memory has drifted from the
    /// hash the kernel was initialised with — which should never happen in
    /// practice, but is checked defensively because constitutional integrity
    /// is a load-bearing invariant.
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::ConstitutionalKernel;
    /// let kernel = ConstitutionalKernel::new();
    /// assert!(kernel.verify_integrity());
    /// ```
    #[must_use]
    pub fn verify_integrity(&self) -> bool {
        self.inner.verify_kernel_integrity(&self.constitution)
    }

    /// Number of constitutional invariants enforced by this kernel (always 8).
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::kernel::ConstitutionalKernel;
    /// assert_eq!(ConstitutionalKernel::new().invariant_count(), 8);
    /// ```
    #[must_use]
    pub fn invariant_count(&self) -> usize {
        INVARIANT_COUNT
    }

    fn signed_authority_link(
        authority: &KernelAuthority,
        grantee: &Did,
        permissions: &PermissionSet,
    ) -> exo_core::Result<AuthorityLink> {
        let mut link = AuthorityLink {
            grantor: authority.did.clone(),
            grantee: grantee.clone(),
            permissions: permissions.clone(),
            signature: Vec::new(),
            grantor_public_key: Some(authority.public_key.as_bytes().to_vec()),
        };
        let message = authority_link_signature_message(&link)?;
        let signature = (authority.signer)(message.as_bytes());
        link.signature = signature.to_bytes().to_vec();
        Ok(link)
    }

    fn signed_provenance(
        authority: &KernelAuthority,
        actor: &Did,
        action: &str,
    ) -> exo_core::Result<Provenance> {
        let timestamp = "sdk".to_owned();
        let action_hash = Hash256::digest(action.as_bytes()).as_bytes().to_vec();

        let mut provenance = Provenance {
            actor: actor.clone(),
            timestamp,
            action_hash,
            signature: Vec::new(),
            public_key: Some(authority.public_key.as_bytes().to_vec()),
            voice_kind: None,
            independence: None,
            review_order: None,
        };
        let message = provenance_signature_message(&provenance)?;
        let signature = (authority.signer)(message.as_bytes());
        provenance.signature = signature.to_bytes().to_vec();
        Ok(provenance)
    }

    fn permission_scope(permissions: &PermissionSet) -> String {
        let mut labels: Vec<&str> = permissions
            .permissions
            .iter()
            .map(|permission| permission.0.as_str())
            .collect();
        labels.sort_unstable();
        labels.dedup();
        labels.join(";")
    }

    fn adjudicate_internal(
        &self,
        actor: &Did,
        action: &str,
        is_self_grant: bool,
        modifies_kernel: bool,
        include_bailment: bool,
        human_override_preserved: bool,
    ) -> KernelVerdict {
        let Some(authority) = self.authority.as_ref() else {
            return KernelVerdict::Denied {
                violations: vec![
                    "AuthorityChainValid: SDK authority signer is required for adjudication".into(),
                ],
            };
        };

        let permissions = PermissionSet::new(vec![Permission::new("read")]);
        let request = ActionRequest {
            actor: actor.clone(),
            action: action.to_owned(),
            required_permissions: permissions.clone(),
            is_self_grant,
            modifies_kernel,
        };

        let scope = Self::permission_scope(&permissions);

        let (bailment_state, consent_records) = if include_bailment {
            (
                BailmentState::Active {
                    bailor: authority.did.clone(),
                    bailee: actor.clone(),
                    scope: scope.clone(),
                },
                vec![ConsentRecord {
                    subject: authority.did.clone(),
                    granted_to: actor.clone(),
                    scope,
                    active: true,
                }],
            )
        } else {
            (BailmentState::None, Vec::new())
        };

        let authority_link = match Self::signed_authority_link(authority, actor, &permissions) {
            Ok(link) => link,
            Err(err) => {
                return KernelVerdict::Denied {
                    violations: vec![format!(
                        "AuthorityChainValid: canonical authority signature payload failed: {err}"
                    )],
                };
            }
        };
        let provenance = match Self::signed_provenance(authority, actor, action) {
            Ok(provenance) => provenance,
            Err(err) => {
                return KernelVerdict::Denied {
                    violations: vec![format!(
                        "ProvenanceVerifiable: canonical provenance signature payload failed: {err}"
                    )],
                };
            }
        };

        let authority_chain = AuthorityChain {
            links: vec![authority_link],
        };
        let mut trusted_authority_keys = TrustedAuthorityKeys::default();
        for link in &authority_chain.links {
            if let Some(public_key) = &link.grantor_public_key {
                trusted_authority_keys.insert(link.grantor.clone(), vec![public_key.clone()]);
            }
        }
        let mut trusted_provenance_keys = TrustedProvenanceKeys::default();
        trusted_provenance_keys.insert(
            actor.clone(),
            vec![authority.public_key.as_bytes().to_vec()],
        );

        let context = AdjudicationContext {
            actor_roles: vec![Role {
                name: "judge".into(),
                branch: GovernmentBranch::Judicial,
            }],
            authority_chain,
            consent_records,
            bailment_state,
            human_override_preserved,
            actor_permissions: permissions,
            trusted_authority_keys,
            trusted_provenance_keys,
            provenance: Some(provenance),
            quorum_evidence: None,
            active_challenge_reason: None,
        };

        match self.inner.adjudicate(&request, &context) {
            Verdict::Permitted => KernelVerdict::Permitted,
            Verdict::Denied { violations } => KernelVerdict::Denied {
                violations: violations
                    .into_iter()
                    .map(|v| format!("{}: {}", v.invariant.id(), v.description))
                    .collect(),
            },
            Verdict::Escalated { reason } => KernelVerdict::Escalated { reason },
        }
    }
}

impl Default for ConstitutionalKernel {
    fn default() -> Self {
        Self::new()
    }
}

impl core::fmt::Debug for ConstitutionalKernel {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ConstitutionalKernel")
            .field("invariant_count", &INVARIANT_COUNT)
            .finish()
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn did(s: &str) -> Did {
        Did::new(s).expect("valid DID")
    }

    fn signed_kernel() -> ConstitutionalKernel {
        ConstitutionalKernel::with_authority_identity(crate::identity::Identity::generate(
            "sdk-authority",
        ))
    }

    #[test]
    fn new_initialises_with_eight_invariants() {
        let k = ConstitutionalKernel::new();
        assert_eq!(k.invariant_count(), 8);
    }

    #[test]
    fn verify_integrity_holds_after_new() {
        let k = ConstitutionalKernel::new();
        assert!(k.verify_integrity());
    }

    #[test]
    fn default_matches_new() {
        let a = ConstitutionalKernel::default();
        let b = ConstitutionalKernel::new();
        assert_eq!(a.invariant_count(), b.invariant_count());
        assert_eq!(a.verify_integrity(), b.verify_integrity());
    }

    #[test]
    fn valid_action_permitted() {
        let k = signed_kernel();
        let actor = did("did:exo:valid-actor");
        let verdict = k.adjudicate(&actor, "read-medical-record");
        assert!(
            verdict.is_permitted(),
            "expected Permitted, got {verdict:?}"
        );
    }

    #[test]
    fn adjudicate_without_authority_signer_fails_closed() {
        let k = ConstitutionalKernel::new();
        let actor = did("did:exo:valid-actor");
        let verdict = k.adjudicate(&actor, "read-medical-record");
        assert!(verdict.is_denied(), "expected Denied, got {verdict:?}");
        match verdict {
            KernelVerdict::Denied { violations } => {
                assert!(violations.iter().any(|v| v.contains("authority signer")));
            }
            other => panic!("expected Denied, got {other:?}"),
        }
    }

    #[test]
    fn self_grant_denied() {
        let k = signed_kernel();
        let actor = did("did:exo:self-granter");
        let verdict = k.adjudicate_self_grant(&actor, "escalate-self");
        assert!(verdict.is_denied(), "expected Denied, got {verdict:?}");
        match verdict {
            KernelVerdict::Denied { violations } => {
                assert!(
                    violations
                        .iter()
                        .any(|violation| violation.starts_with("no-self-grant: ")),
                    "violations must use stable invariant IDs: {violations:?}"
                );
            }
            other => panic!("expected Denied, got {other:?}"),
        }
    }

    #[test]
    fn kernel_modification_denied() {
        let k = signed_kernel();
        let actor = did("did:exo:patcher");
        let verdict = k.adjudicate_kernel_modification(&actor, "patch-kernel");
        assert!(verdict.is_denied(), "expected Denied, got {verdict:?}");
    }

    #[test]
    fn no_bailment_denied() {
        let k = signed_kernel();
        let actor = did("did:exo:unauth");
        let verdict = k.adjudicate_without_bailment(&actor, "read-data");
        assert!(verdict.is_denied(), "expected Denied, got {verdict:?}");
    }

    #[test]
    fn sdk_violation_labels_do_not_depend_on_debug_formatting() {
        let source = include_str!("kernel.rs")
            .split("// ===========================================================================\n// Tests")
            .next()
            .expect("production section");
        assert!(
            !source.contains("format!(\"{:?}: {}\", v.invariant, v.description)"),
            "SDK violation labels must use stable invariant IDs"
        );
    }

    #[test]
    fn verdict_helpers() {
        assert!(KernelVerdict::Permitted.is_permitted());
        assert!(!KernelVerdict::Permitted.is_denied());
        let denied = KernelVerdict::Denied { violations: vec![] };
        assert!(denied.is_denied());
        assert!(!denied.is_permitted());
        let esc = KernelVerdict::Escalated { reason: "r".into() };
        assert!(esc.is_escalated());
        assert!(!esc.is_permitted());
    }

    #[test]
    fn verdict_serde_roundtrip() {
        let v = KernelVerdict::Denied {
            violations: vec!["NoSelfGrant: reason".into()],
        };
        let json = serde_json::to_string(&v).expect("ser");
        let decoded: KernelVerdict = serde_json::from_str(&json).expect("de");
        assert_eq!(v, decoded);
    }

    #[test]
    fn debug_impl_smoke() {
        let k = ConstitutionalKernel::new();
        let dbg = format!("{k:?}");
        assert!(dbg.contains("ConstitutionalKernel"));
        assert!(dbg.contains("8"));
    }
}