Skip to main content

ggen_core/
genesis.rs

1//! Genesis Core Primitives (Heap-free and no-std friendly)
2//!
3//! This module implements key primitives for the Genesis embedded core and ggen's outer membrane:
4//! - [`Pair2`]: Bounded relationship tuple of two entities with optional timestamp
5//! - [`SymbolDomain`]: Deterministic tracking of up to 256 unique symbols per domain
6//! - [`Multiplicity`]: Enum controlling whether domains allow duplicates, bags, streams, or event addressing
7//! - [`PageSplit`]: Deterministic partition of a RelationPage when domain saturates
8//! - [`RelationPage`]: Fixed-size heap-free index of relationships with domain bounds enforcement
9//! - [`Construct8`]: Bounded kinetic delta primitive (subject, predicate, object, graph, mask, provenance, admission, receipt_hint)
10//! - [`Receipt`]: Cryptographically signed, heap-free execution receipt
11//! - [`Replay`]: Deterministic execution replay log and engine
12//! - [`Refusal`]: Concrete out-of-manifold execution refusal with observed boundary evidence
13
14// No longer no_std at mod level
15
16use core::fmt;
17
18/// Size constants for heap-free layout boundaries
19pub const MAX_RELATION_PAIRS: usize = 8;
20pub const MAX_REPLAY_STEPS: usize = 16;
21pub const IDENTIFIER_SIZE: usize = 8;
22pub const HASH_SIZE: usize = 32;
23pub const SIGNATURE_SIZE: usize = 64;
24pub const MAX_DOMAIN_SYMBOLS: usize = 256;
25
26// --- Newtype wrappers around [u8; 8] for Construct8 ---
27
28/// Bounded Subject Node Identifier (8 bytes)
29#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct Node8(pub [u8; IDENTIFIER_SIZE]);
31
32/// Bounded Predicate Identifier (8 bytes)
33#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct Predicate8(pub [u8; IDENTIFIER_SIZE]);
35
36/// Bounded Object Identifier (8 bytes)
37#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct Object8(pub [u8; IDENTIFIER_SIZE]);
39
40/// Bounded Graph/Partition Identifier (8 bytes)
41#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Graph8(pub [u8; IDENTIFIER_SIZE]);
43
44/// Bounded Execution Mask / Capability (8 bytes)
45#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct Mask8(pub [u8; IDENTIFIER_SIZE]);
47
48/// Bounded Provenance Link (8 bytes)
49#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub struct Provenance8(pub [u8; IDENTIFIER_SIZE]);
51
52/// Bounded Admission Token / Checksum (8 bytes)
53#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct Admission8(pub [u8; IDENTIFIER_SIZE]);
55
56/// Bounded Cryptographic Receipt Hint / Salt (8 bytes)
57#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct ReceiptHint8(pub [u8; IDENTIFIER_SIZE]);
59
60// Implementations of helper display and creation methods for Node8 etc.
61macro_rules! impl_newtype_helpers {
62    ($t:ident, $name:expr) => {
63        impl $t {
64            /// Create from a literal slice
65            pub const fn from_bytes(bytes: [u8; IDENTIFIER_SIZE]) -> Self {
66                Self(bytes)
67            }
68
69            /// Expose the underlying byte representation
70            pub const fn as_bytes(&self) -> &[u8; IDENTIFIER_SIZE] {
71                &self.0
72            }
73        }
74
75        impl fmt::Debug for $t {
76            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77                write!(f, "{}(hex: ", $name)?;
78                for byte in &self.0 {
79                    write!(f, "{:02x}", byte)?;
80                }
81                write!(f, ")")
82            }
83        }
84    };
85}
86
87impl_newtype_helpers!(Node8, "Node8");
88impl_newtype_helpers!(Predicate8, "Predicate8");
89impl_newtype_helpers!(Object8, "Object8");
90impl_newtype_helpers!(Graph8, "Graph8");
91impl_newtype_helpers!(Mask8, "Mask8");
92impl_newtype_helpers!(Provenance8, "Provenance8");
93impl_newtype_helpers!(Admission8, "Admission8");
94impl_newtype_helpers!(ReceiptHint8, "ReceiptHint8");
95
96// --- Multiplicity & SymbolDomain ---
97
98/// Multiplicity enum controlling insertion semantics for domain tracking
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[repr(u8)]
101pub enum Multiplicity {
102    /// Set semantics: duplicate pairs rejected
103    Set = 0,
104    /// Bag semantics: duplicate pairs allowed, counted
105    Bag = 1,
106    /// Stream semantics: temporal ordering matters, timestamps tracked
107    Stream = 2,
108    /// Event-addressed semantics: event_id distinguishes duplicates
109    EventAddressed = 3,
110}
111
112impl Multiplicity {
113    /// Returns whether this multiplicity allows duplicate pairs
114    pub fn allows_duplicates(&self) -> bool {
115        matches!(
116            self,
117            Multiplicity::Bag | Multiplicity::Stream | Multiplicity::EventAddressed
118        )
119    }
120}
121
122/// SymbolDomain: Deterministic tracking of up to 256 unique symbols
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct SymbolDomain {
125    /// Storage for up to 256 unique symbols (8 bytes each)
126    pub symbols: [Option<[u8; 8]>; MAX_DOMAIN_SYMBOLS],
127    /// Count of symbols currently in domain
128    pub count: u16,
129}
130
131impl SymbolDomain {
132    /// Create a new empty domain
133    pub const fn new() -> Self {
134        Self {
135            symbols: [None; MAX_DOMAIN_SYMBOLS],
136            count: 0,
137        }
138    }
139
140    /// Insert a symbol into the domain. Returns Ok(true) if newly inserted, Ok(false) if already present.
141    /// Returns Err(RefusalCode::PageSplitRequired) if domain is at capacity.
142    pub fn insert(&mut self, symbol: [u8; 8]) -> Result<bool, RefusalCode> {
143        // Check if already present
144        for i in 0..self.count as usize {
145            if let Some(existing) = self.symbols[i] {
146                if existing == symbol {
147                    return Ok(false); // Already present
148                }
149            }
150        }
151
152        // Check capacity
153        if self.count >= MAX_DOMAIN_SYMBOLS as u16 {
154            return Err(RefusalCode::PageSplitRequired);
155        }
156
157        // Insert new symbol
158        self.symbols[self.count as usize] = Some(symbol);
159        self.count += 1;
160        Ok(true)
161    }
162
163    /// Check if symbol exists in domain
164    pub fn contains(&self, symbol: &[u8; 8]) -> bool {
165        for i in 0..self.count as usize {
166            if let Some(existing) = self.symbols[i] {
167                if &existing == symbol {
168                    return true;
169                }
170            }
171        }
172        false
173    }
174
175    /// Count of symbols in domain
176    pub fn count(&self) -> usize {
177        self.count as usize
178    }
179}
180
181impl Default for SymbolDomain {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187// --- PageSplit ---
188
189/// PageSplit: Result of deterministic page partitioning when domain saturates
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct PageSplit {
192    /// Hash of source page before split
193    pub source_page_hash: [u8; HASH_SIZE],
194    /// Left partition page hash
195    pub left_page_hash: [u8; HASH_SIZE],
196    /// Right partition page hash
197    pub right_page_hash: [u8; HASH_SIZE],
198    /// Timestamp of split operation
199    pub timestamp: u64,
200}
201
202impl PageSplit {
203    /// Perform deterministic page split using modulo-2 strategy on subject bytes
204    pub fn split(
205        _source_page: &RelationPage, source_hash: [u8; HASH_SIZE], time: u64,
206    ) -> Result<Self, RefusalCode> {
207        // Compute left and right hashes from source content
208        // In a real implementation, these would be derived from the partition
209        let mut left_hash = [0u8; HASH_SIZE];
210        let mut right_hash = [0u8; HASH_SIZE];
211
212        // Simple deterministic hash computation: XOR first 16 bytes with pattern
213        for i in 0..16 {
214            left_hash[i] = source_hash[i] ^ 0xAA;
215            right_hash[i] = source_hash[i] ^ 0x55;
216        }
217
218        Ok(PageSplit {
219            source_page_hash: source_hash,
220            left_page_hash: left_hash,
221            right_page_hash: right_hash,
222            timestamp: time,
223        })
224    }
225}
226
227// --- Pair2 & RelationPage ---
228
229/// Pair2: A bounded semantic binary relationship (e.g. subject-object connection)
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231pub struct Pair2 {
232    /// Source / Subject entity
233    pub subject: Node8,
234    /// Destination / Object entity
235    pub object: Node8,
236    /// Optional timestamp for temporal semantics (Stream multiplicity)
237    pub timestamp: Option<u64>,
238    /// Optional event ID for event-addressed semantics (EventAddressed multiplicity)
239    pub event_id: Option<[u8; 8]>,
240}
241
242impl Pair2 {
243    /// Create a new semantic connection
244    pub const fn new(subject: Node8, object: Node8) -> Self {
245        Self {
246            subject,
247            object,
248            timestamp: None,
249            event_id: None,
250        }
251    }
252
253    /// Create a new Pair2 with timestamp (Stream multiplicity)
254    pub const fn with_timestamp(subject: Node8, object: Node8, timestamp: u64) -> Self {
255        Self {
256            subject,
257            object,
258            timestamp: Some(timestamp),
259            event_id: None,
260        }
261    }
262
263    /// Create a new Pair2 with event_id (EventAddressed multiplicity)
264    pub const fn with_event_id(subject: Node8, object: Node8, event_id: [u8; 8]) -> Self {
265        Self {
266            subject,
267            object,
268            timestamp: None,
269            event_id: Some(event_id),
270        }
271    }
272
273    /// Serialize to bytes for deterministic hashing (little-endian timestamp if present)
274    pub fn to_bytes(&self) -> [u8; 32] {
275        let mut out = [0u8; 32];
276        out[0..8].copy_from_slice(self.subject.as_bytes());
277        out[8..16].copy_from_slice(self.object.as_bytes());
278
279        if let Some(ts) = self.timestamp {
280            out[16..24].copy_from_slice(&ts.to_le_bytes());
281        }
282        if let Some(eid) = self.event_id {
283            out[24..32].copy_from_slice(&eid);
284        }
285        out
286    }
287
288    /// Compare two Pair2s ignoring metadata (timestamp and event_id)
289    pub fn pairs_equal_ignoring_metadata(&self, other: &Pair2) -> bool {
290        self.subject == other.subject && self.object == other.object
291    }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295pub struct CompactPair {
296    pub subject_symbol: u8,
297    pub object_symbol: u8,
298}
299
300/// RelationPage: A heap-free, fixed-size container representing a page/index of relationships
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct RelationPage {
303    pub pairs: [Option<CompactPair>; MAX_RELATION_PAIRS],
304    pub length: usize,
305    pub left_symbols: [Option<Node8>; 256],
306    pub right_symbols: [Option<Node8>; 256],
307    pub left_len: usize,
308    pub right_len: usize,
309    /// Left domain tracking with bounds enforcement
310    pub left_domain: SymbolDomain,
311    /// Right domain tracking with bounds enforcement
312    pub right_domain: SymbolDomain,
313    /// Multiplicity mode controlling insertion semantics
314    pub multiplicity: Multiplicity,
315    /// Pair counts for Bag multiplicity (count per pair index)
316    pub pair_counts: [u32; 32],
317}
318
319impl RelationPage {
320    /// Initialize an empty relation page
321    pub const fn new() -> Self {
322        Self {
323            pairs: [None; MAX_RELATION_PAIRS],
324            length: 0,
325            left_symbols: [None; 256],
326            right_symbols: [None; 256],
327            left_len: 0,
328            right_len: 0,
329            left_domain: SymbolDomain {
330                symbols: [None; MAX_DOMAIN_SYMBOLS],
331                count: 0,
332            },
333            right_domain: SymbolDomain {
334                symbols: [None; MAX_DOMAIN_SYMBOLS],
335                count: 0,
336            },
337            multiplicity: Multiplicity::Set,
338            pair_counts: [0u32; 32],
339        }
340    }
341}
342
343impl Default for RelationPage {
344    fn default() -> Self {
345        Self::new()
346    }
347}
348
349impl RelationPage {
350    /// Initialize with specific multiplicity mode
351    pub fn with_multiplicity(multiplicity: Multiplicity) -> Self {
352        let mut page = Self::new();
353        page.multiplicity = multiplicity;
354        page
355    }
356
357    /// Insert a new relationship pair. Returns `true` if inserted, `false` if full or duplicate.
358    /// Enforces domain bounds and multiplicity constraints.
359    pub fn insert(&mut self, pair: Pair2) -> bool {
360        // Track domains before insertion
361        let subject_bytes = pair.subject.as_bytes();
362        let object_bytes = pair.object.as_bytes();
363
364        // For domain bounds enforcement, try to insert into domains
365        // If domain is at capacity, return false (would trigger PageSplitRequired in caller)
366        if !self.left_domain.contains(subject_bytes) {
367            if self.left_domain.insert(*subject_bytes).is_err() {
368                return false; // Domain saturation
369            }
370        }
371
372        if !self.right_domain.contains(object_bytes) {
373            if self.right_domain.insert(*object_bytes).is_err() {
374                return false; // Domain saturation
375            }
376        }
377
378        // Legacy symbol tracking for backward compatibility
379        let mut subject_symbol = None;
380        for i in 0..self.left_len {
381            if let Some(ref sym) = self.left_symbols[i] {
382                if sym == &pair.subject {
383                    subject_symbol = Some(i as u8);
384                    break;
385                }
386            }
387        }
388        let subject_symbol = match subject_symbol {
389            Some(sym) => sym,
390            None => {
391                if self.left_len >= 256 {
392                    return false;
393                }
394                self.left_symbols[self.left_len] = Some(pair.subject);
395                let sym = self.left_len as u8;
396                self.left_len += 1;
397                sym
398            }
399        };
400
401        let mut object_symbol = None;
402        for i in 0..self.right_len {
403            if let Some(ref sym) = self.right_symbols[i] {
404                if sym == &pair.object {
405                    object_symbol = Some(i as u8);
406                    break;
407                }
408            }
409        }
410        let object_symbol = match object_symbol {
411            Some(sym) => sym,
412            None => {
413                if self.right_len >= 256 {
414                    return false;
415                }
416                self.right_symbols[self.right_len] = Some(pair.object);
417                let sym = self.right_len as u8;
418                self.right_len += 1;
419                sym
420            }
421        };
422
423        let compact = CompactPair {
424            subject_symbol,
425            object_symbol,
426        };
427
428        // Check for duplicates based on multiplicity
429        for i in 0..MAX_RELATION_PAIRS {
430            if let Some(ref p) = self.pairs[i] {
431                if p == &compact {
432                    // If multiplicity allows duplicates, increment count instead
433                    if self.multiplicity.allows_duplicates() && i < 32 {
434                        self.pair_counts[i] += 1;
435                        return true;
436                    }
437                    return false; // Set semantics: duplicate rejected
438                }
439            }
440        }
441
442        // Find an empty slot
443        for i in 0..MAX_RELATION_PAIRS {
444            if self.pairs[i].is_none() {
445                self.pairs[i] = Some(compact);
446                if i < 32 {
447                    self.pair_counts[i] = 1;
448                }
449                self.length += 1;
450                return true;
451            }
452        }
453        false // Page is full
454    }
455
456    /// Check if a pair exists in the page
457    pub fn contains(&self, pair: &Pair2) -> bool {
458        let mut subject_symbol = None;
459        for i in 0..self.left_len {
460            if let Some(ref sym) = self.left_symbols[i] {
461                if sym == &pair.subject {
462                    subject_symbol = Some(i as u8);
463                    break;
464                }
465            }
466        }
467        let Some(s_sym) = subject_symbol else {
468            return false;
469        };
470
471        let mut object_symbol = None;
472        for i in 0..self.right_len {
473            if let Some(ref sym) = self.right_symbols[i] {
474                if sym == &pair.object {
475                    object_symbol = Some(i as u8);
476                    break;
477                }
478            }
479        }
480        let Some(o_sym) = object_symbol else {
481            return false;
482        };
483
484        let compact = CompactPair {
485            subject_symbol: s_sym,
486            object_symbol: o_sym,
487        };
488
489        for i in 0..MAX_RELATION_PAIRS {
490            if let Some(ref p) = self.pairs[i] {
491                if p == &compact {
492                    return true;
493                }
494            }
495        }
496        false
497    }
498
499    /// Remove a relationship pair. Returns `true` if found and removed.
500    pub fn remove(&mut self, pair: &Pair2) -> bool {
501        let mut subject_symbol = None;
502        for i in 0..self.left_len {
503            if let Some(ref sym) = self.left_symbols[i] {
504                if sym == &pair.subject {
505                    subject_symbol = Some(i as u8);
506                    break;
507                }
508            }
509        }
510        let Some(s_sym) = subject_symbol else {
511            return false;
512        };
513
514        let mut object_symbol = None;
515        for i in 0..self.right_len {
516            if let Some(ref sym) = self.right_symbols[i] {
517                if sym == &pair.object {
518                    object_symbol = Some(i as u8);
519                    break;
520                }
521            }
522        }
523        let Some(o_sym) = object_symbol else {
524            return false;
525        };
526
527        let compact = CompactPair {
528            subject_symbol: s_sym,
529            object_symbol: o_sym,
530        };
531
532        for i in 0..MAX_RELATION_PAIRS {
533            if let Some(ref p) = self.pairs[i] {
534                if p == &compact {
535                    self.pairs[i] = None;
536                    self.length -= 1;
537                    return true;
538                }
539            }
540        }
541        false
542    }
543}
544
545// --- Construct8 ---
546
547/// Construct8: Bounded constructive state projection/delta primitive.
548/// It defines a kinetic delta that moves between graph truth and execution.
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
550pub struct Construct8 {
551    /// Bounded subject
552    pub subject: Node8,
553    /// Bounded predicate
554    pub predicate: Predicate8,
555    /// Bounded object
556    pub object: Object8,
557    /// Bounded graph target
558    pub graph: Graph8,
559    /// Bounded capability mask
560    pub mask: Mask8,
561    /// Provenance tag
562    pub provenance: Provenance8,
563    /// Admission validator token
564    pub admission: Admission8,
565    /// Cryptographic receipt verification hint
566    pub receipt_hint: ReceiptHint8,
567}
568
569impl Construct8 {
570    #[allow(clippy::too_many_arguments)] // Eight-tuple construct requires all eight semantic fields
571    pub fn new(
572        subject: Node8, predicate: Predicate8, object: Object8, graph: Graph8, mask: Mask8,
573        provenance: Provenance8, admission: Admission8, receipt_hint: ReceiptHint8,
574    ) -> Self {
575        Self {
576            subject,
577            predicate,
578            object,
579            graph,
580            mask,
581            provenance,
582            admission,
583            receipt_hint,
584        }
585    }
586
587    /// Serialize structural representation to bytes for hashing
588    pub fn to_bytes(&self) -> [u8; 64] {
589        let mut out = [0u8; 64];
590        out[0..8].copy_from_slice(self.subject.as_bytes());
591        out[8..16].copy_from_slice(self.predicate.as_bytes());
592        out[16..24].copy_from_slice(self.object.as_bytes());
593        out[24..32].copy_from_slice(self.graph.as_bytes());
594        out[32..40].copy_from_slice(self.mask.as_bytes());
595        out[40..48].copy_from_slice(self.provenance.as_bytes());
596        out[48..56].copy_from_slice(self.admission.as_bytes());
597        out[56..64].copy_from_slice(self.receipt_hint.as_bytes());
598        out
599    }
600}
601
602// --- Receipt ---
603
604/// Receipt: Heap-free cryptographic execution receipt, containing observed boundary evidence.
605#[derive(Clone, Copy, PartialEq, Eq)]
606pub struct Receipt {
607    /// Operation identity hash/checksum
608    pub operation_id: [u8; 16],
609    /// Cryptographic hash of observed boundary inputs
610    pub inputs_hash: [u8; HASH_SIZE],
611    /// Cryptographic hash of produced boundary outputs
612    pub outputs_hash: [u8; HASH_SIZE],
613    /// Optional parent receipt hash for causal linking
614    pub previous_receipt_hash: Option<[u8; HASH_SIZE]>,
615    /// Digital signature of receipt contents
616    pub signature: Option<[u8; SIGNATURE_SIZE]>,
617    /// Verizable public key of the signer
618    pub public_key: Option<[u8; 32]>,
619    /// Deterministic epoch timestamp
620    pub timestamp: u64,
621}
622
623impl fmt::Debug for Receipt {
624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625        f.debug_struct("Receipt")
626            .field("operation_id", &self.operation_id)
627            .field("inputs_hash", &HexSlice(&self.inputs_hash))
628            .field("outputs_hash", &HexSlice(&self.outputs_hash))
629            .field(
630                "previous_receipt_hash",
631                &self.previous_receipt_hash.as_ref().map(HexSlice),
632            )
633            .field("signature", &self.signature.as_ref().map(HexSlice64))
634            .field("public_key", &self.public_key.as_ref().map(HexSlice))
635            .field("timestamp", &self.timestamp)
636            .finish()
637    }
638}
639
640struct HexSlice<'a>(&'a [u8; HASH_SIZE]);
641impl fmt::Debug for HexSlice<'_> {
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        for byte in self.0 {
644            write!(f, "{:02x}", byte)?;
645        }
646        Ok(())
647    }
648}
649
650struct HexSlice64<'a>(&'a [u8; SIGNATURE_SIZE]);
651impl fmt::Debug for HexSlice64<'_> {
652    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653        for byte in self.0 {
654            write!(f, "{:02x}", byte)?;
655        }
656        Ok(())
657    }
658}
659
660impl Receipt {
661    /// Create a new, unsigned Receipt with actual observed hashes
662    pub const fn new(
663        operation_id: [u8; 16], inputs_hash: [u8; HASH_SIZE], outputs_hash: [u8; HASH_SIZE],
664        previous_receipt_hash: Option<[u8; HASH_SIZE]>, timestamp: u64,
665    ) -> Self {
666        Self {
667            operation_id,
668            inputs_hash,
669            outputs_hash,
670            previous_receipt_hash,
671            signature: None,
672            public_key: None,
673            timestamp,
674        }
675    }
676
677    /// Calculate hash over receipt contents (excluding signature field)
678    pub fn calculate_hash(&self) -> [u8; HASH_SIZE] {
679        let mut hasher = blake3::Hasher::new();
680        hasher.update(&self.operation_id);
681        hasher.update(&self.inputs_hash);
682        hasher.update(&self.outputs_hash);
683        if let Some(prev) = self.previous_receipt_hash {
684            hasher.update(&prev);
685        } else {
686            hasher.update(&[0u8; HASH_SIZE]);
687        }
688        hasher.update(&self.timestamp.to_le_bytes());
689        *hasher.finalize().as_bytes()
690    }
691
692    /// Sign the receipt payload using Ed25519
693    pub fn sign(mut self, signing_key: &ed25519_dalek::SigningKey) -> Self {
694        use ed25519_dalek::Signer;
695        let hash = self.calculate_hash();
696        let sig = signing_key.sign(&hash);
697        self.signature = Some(sig.to_bytes());
698        self.public_key = Some(signing_key.verifying_key().to_bytes());
699        self
700    }
701
702    /// Verify signature and structure authenticity
703    pub fn verify(&self) -> Result<(), RefusalCode> {
704        use ed25519_dalek::Verifier;
705        let pk_bytes = self
706            .public_key
707            .ok_or(RefusalCode::BoundaryEvidenceMissing)?;
708        let sig_bytes = self.signature.ok_or(RefusalCode::BoundaryEvidenceMissing)?;
709
710        let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
711            .map_err(|_| RefusalCode::InvalidSignature)?;
712        let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);
713
714        let hash = self.calculate_hash();
715        verifying_key
716            .verify(&hash, &signature)
717            .map_err(|_| RefusalCode::InvalidSignature)
718    }
719}
720
721// --- Refusal ---
722
723/// RefusalReason classifying state refusal boundaries
724#[derive(Debug, Clone, Copy, PartialEq, Eq)]
725#[repr(u8)]
726pub enum RefusalCode {
727    /// Missing vital boundary evidence/hash
728    BoundaryEvidenceMissing = 1,
729    /// Required OCEL-shaped tracing trace missing
730    ExpectedOCELMissing = 2,
731    /// Missing tool call cryptographic hash
732    ToolCallHashMissing = 3,
733    /// Invalid signature on execution/receipt gate
734    InvalidSignature = 4,
735    /// Inconsistent parent/child causal receipt links
736    CausalInconsistency = 5,
737    /// Delta/Mask constraint violation
738    ConstraintViolation = 6,
739    /// Page split required: domain saturation reached
740    PageSplitRequired = 7,
741    /// Domain bounds exceeded: symbol limit reached
742    DomainBoundsExceeded = 8,
743}
744
745/// Refusal: Concrete out-of-manifold execution refusal with observed boundary evidence
746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub struct Refusal {
748    /// Specific failure code
749    pub code: RefusalCode,
750    /// Cryptographic hash of the operation being refused
751    pub op_hash: [u8; HASH_SIZE],
752    /// Actual observed evidence bytes up to the point of failure
753    pub evidence: [u8; 64],
754    /// Refusal occurrence timestamp
755    pub timestamp: u64,
756}
757
758impl Refusal {
759    /// Create a new refusal binding concrete evidence
760    pub const fn new(
761        code: RefusalCode, op_hash: [u8; HASH_SIZE], evidence: [u8; 64], timestamp: u64,
762    ) -> Self {
763        Self {
764            code,
765            op_hash,
766            evidence,
767            timestamp,
768        }
769    }
770}
771
772// --- Replay ---
773
774/// Replay: Deterministic execution log structure
775#[derive(Debug, Clone, PartialEq, Eq)]
776pub struct Replay {
777    /// Sequence of target Construct8 deltas
778    pub steps: [Option<Construct8>; MAX_REPLAY_STEPS],
779    /// Actual count of delta steps stored
780    pub length: usize,
781}
782
783impl Replay {
784    /// Create an empty replay log
785    pub const fn new() -> Self {
786        Self {
787            steps: [None; MAX_REPLAY_STEPS],
788            length: 0,
789        }
790    }
791}
792
793impl Default for Replay {
794    fn default() -> Self {
795        Self::new()
796    }
797}
798
799impl Replay {
800    /// Add a Construct8 delta step
801    pub fn push(&mut self, step: Construct8) -> bool {
802        if self.length >= MAX_REPLAY_STEPS {
803            return false;
804        }
805        self.steps[self.length] = Some(step);
806        self.length += 1;
807        true
808    }
809
810    /// Replay the step sequence deterministically onto a target RelationPage state.
811    /// Returns the updated state on success, or a concrete `Refusal` on failure.
812    pub fn run(&self, mut state: RelationPage, current_time: u64) -> Result<RelationPage, Refusal> {
813        for i in 0..self.length {
814            if let Some(ref step) = self.steps[i] {
815                // Check capability mask: validation constraint
816                // We enforce that the mask cannot be all zeros [0, 0, 0, 0, 0, 0, 0, 0]
817                if step.mask.as_bytes() == &[0u8; IDENTIFIER_SIZE] {
818                    let mut op_hash = [0u8; HASH_SIZE];
819                    op_hash[0..8].copy_from_slice(step.subject.as_bytes());
820                    op_hash[8..16].copy_from_slice(step.predicate.as_bytes());
821                    return Err(Refusal::new(
822                        RefusalCode::ConstraintViolation,
823                        op_hash,
824                        step.to_bytes(),
825                        current_time,
826                    ));
827                }
828
829                // Mutate state: insert the semantic subject-object link
830                let pair = Pair2::new(step.subject, Node8::from_bytes(*step.object.as_bytes()));
831                if !state.insert(pair) {
832                    // Fail if page is full or can't be processed
833                    let mut op_hash = [0u8; HASH_SIZE];
834                    op_hash[0..8].copy_from_slice(step.subject.as_bytes());
835                    op_hash[8..16].copy_from_slice(step.predicate.as_bytes());
836                    return Err(Refusal::new(
837                        RefusalCode::ConstraintViolation,
838                        op_hash,
839                        step.to_bytes(),
840                        current_time,
841                    ));
842                }
843            }
844        }
845        Ok(state)
846    }
847}