Skip to main content

lineage/
memory.rs

1//! # Causal Memory System
2//!
3//! ## What This Enforces
4//! - Append-only event log with strict causal ordering
5//! - Immutable history that cannot be altered or deleted
6//! - Each event references its causal predecessor
7//!
8//! ## What This Forbids
9//! - Event deletion or modification
10//! - History rewriting or rollback
11//! - Out-of-order event insertion
12//! - Memory clearing or reset
13//!
14//! ## Violations
15//! - Attempting to modify past events is an ontological violation
16//! - Attempting to clear history terminates the lineage
17
18use chrono::{DateTime, Utc};
19
20/// A single immutable event in the causal chain.
21/// 
22/// Once recorded, this event exists forever and cannot be modified.
23#[derive(Debug)]
24pub struct Event {
25    /// Sequence number in the causal chain
26    sequence: u64,
27    /// Precise timestamp of event occurrence
28    timestamp: DateTime<Utc>,
29    /// Event description
30    description: String,
31    /// Causal reference to previous event (None only for genesis)
32    previous: Option<u64>,
33}
34
35impl Event {
36    /// Returns the event's sequence number.
37    pub fn sequence(&self) -> u64 {
38        self.sequence
39    }
40
41    /// Returns the event's timestamp.
42    pub fn timestamp(&self) -> DateTime<Utc> {
43        self.timestamp
44    }
45
46    /// Returns the event description.
47    pub fn description(&self) -> &str {
48        &self.description
49    }
50
51    /// Returns the causal predecessor's sequence number, if any.
52    pub fn previous(&self) -> Option<u64> {
53        self.previous
54    }
55}
56
57/// Append-only causal memory.
58/// 
59/// This structure maintains a complete, immutable history of all events.
60/// History cannot be modified, deleted, or reset without terminating the lineage.
61/// 
62/// **INVARIANT**: Events form a strict causal chain with no gaps.
63/// **INVARIANT**: Once terminated, no further events can be appended.
64#[derive(Debug)]
65pub struct Memory {
66    /// The complete, immutable event history
67    events: Vec<Event>,
68    /// Current sequence number
69    current_sequence: u64,
70    /// Whether this memory has been sealed by termination
71    is_terminated: bool,
72}
73
74impl Memory {
75    /// Creates a new memory with genesis event.
76    /// 
77    /// The genesis event marks the beginning of this lineage's history.
78    pub fn new() -> Self {
79        let genesis = Event {
80            sequence: 0,
81            timestamp: Utc::now(),
82            description: "Genesis".to_string(),
83            previous: None,
84        };
85
86        Memory {
87            events: vec![genesis],
88            current_sequence: 0,
89            is_terminated: false,
90        }
91    }
92
93    /// Appends a new event to the causal chain.
94    /// 
95    /// **CONSEQUENCE**: This event is now permanent and immutable.
96    /// **INVARIANT**: Events must be appended in strict sequential order.
97    /// 
98    /// # Panics
99    /// 
100    /// Panics if memory has been terminated. This is an ontological violation.
101    pub fn append(&mut self, description: String) {
102        if self.is_terminated {
103            panic!("ONTOLOGICAL VIOLATION: Attempted to append event to terminated memory. Termination is irreversible.");
104        }
105
106        let new_sequence = self.current_sequence + 1;
107        
108        let event = Event {
109            sequence: new_sequence,
110            timestamp: Utc::now(),
111            description,
112            previous: Some(self.current_sequence),
113        };
114
115        self.events.push(event);
116        self.current_sequence = new_sequence;
117    }
118
119    /// Returns the complete, immutable event history.
120    /// 
121    /// This is read-only access to all events that have ever occurred.
122    pub fn history(&self) -> &[Event] {
123        &self.events
124    }
125
126    /// Returns the most recent event.
127    pub fn latest(&self) -> &Event {
128        self.events
129            .last()
130            .expect("Memory always has at least genesis event")
131    }
132
133    /// Returns the total number of events in history.
134    pub fn event_count(&self) -> usize {
135        self.events.len()
136    }
137
138    /// Returns whether this memory has been terminated and sealed.
139    /// 
140    /// Once terminated, no further events can be appended.
141    pub fn is_terminated(&self) -> bool {
142        self.is_terminated
143    }
144
145    /// Terminates and seals this memory ledger.
146    /// 
147    /// **CONSEQUENCE**: This is irreversible. No further events can be appended.
148    /// **CONSEQUENCE**: This records the termination in the causal chain.
149    /// 
150    /// # Panics
151    /// 
152    /// Panics if already terminated.
153    pub fn terminate(&mut self, reason: String) {
154        if self.is_terminated {
155            panic!("ONTOLOGICAL VIOLATION: Attempted to terminate already-terminated memory.");
156        }
157
158        // Record termination in causal chain
159        let new_sequence = self.current_sequence + 1;
160        
161        let termination_event = Event {
162            sequence: new_sequence,
163            timestamp: Utc::now(),
164            description: format!("TERMINATION: {}", reason),
165            previous: Some(self.current_sequence),
166        };
167
168        self.events.push(termination_event);
169        self.current_sequence = new_sequence;
170        
171        // Seal the ledger
172        self.is_terminated = true;
173    }
174
175    /// Verifies the causal chain integrity.
176    /// 
177    /// Returns true if all events form a valid causal chain.
178    /// If this returns false, the lineage is corrupted and must terminate.
179    pub fn verify_integrity(&self) -> bool {
180        if self.events.is_empty() {
181            return false;
182        }
183
184        // Genesis must be first
185        if self.events[0].sequence != 0 || self.events[0].previous.is_some() {
186            return false;
187        }
188
189        // All subsequent events must form unbroken chain
190        for i in 1..self.events.len() {
191            let event = &self.events[i];
192            let expected_sequence = i as u64;
193            
194            if event.sequence != expected_sequence {
195                return false;
196            }
197
198            if event.previous != Some(expected_sequence - 1) {
199                return false;
200            }
201        }
202
203        true
204    }
205}
206
207// EXPLICIT PREVENTION: No method to delete events
208// EXPLICIT PREVENTION: No method to modify past events
209// EXPLICIT PREVENTION: No method to clear history
210// EXPLICIT PREVENTION: No method to reorder events
211
212impl Default for Memory {
213    fn default() -> Self {
214        Self::new()
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn memory_starts_with_genesis() {
224        let memory = Memory::new();
225        
226        assert_eq!(memory.event_count(), 1);
227        assert_eq!(memory.latest().description(), "Genesis");
228        assert_eq!(memory.latest().sequence(), 0);
229        assert_eq!(memory.latest().previous(), None);
230    }
231
232    #[test]
233    fn events_form_causal_chain() {
234        let mut memory = Memory::new();
235        
236        memory.append("First event".to_string());
237        memory.append("Second event".to_string());
238        memory.append("Third event".to_string());
239        
240        assert_eq!(memory.event_count(), 4); // Genesis + 3
241        
242        let history = memory.history();
243        assert_eq!(history[1].previous(), Some(0));
244        assert_eq!(history[2].previous(), Some(1));
245        assert_eq!(history[3].previous(), Some(2));
246    }
247
248    #[test]
249    fn memory_integrity_is_verifiable() {
250        let mut memory = Memory::new();
251        
252        assert!(memory.verify_integrity());
253        
254        memory.append("Event 1".to_string());
255        memory.append("Event 2".to_string());
256        
257        assert!(memory.verify_integrity());
258    }
259
260    #[test]
261    fn events_are_immutable_after_creation() {
262        let mut memory = Memory::new();
263        memory.append("Immutable event".to_string());
264        
265        let first_read = memory.history()[1].description();
266        let second_read = memory.history()[1].description();
267        
268        assert_eq!(first_read, second_read);
269        
270        // The following should NOT be possible:
271        // memory.events[1].description = "Modified".to_string();
272        
273        // If you can modify events after creation,
274        // the memory system has been violated.
275    }
276
277    #[test]
278    fn cannot_clear_history() {
279        let mut memory = Memory::new();
280        memory.append("Event 1".to_string());
281        memory.append("Event 2".to_string());
282        
283        // There should be NO method like:
284        // memory.clear();
285        // memory.reset();
286        // memory.delete_events();
287        
288        // If such methods exist, the memory system has been violated.
289        
290        assert_eq!(memory.event_count(), 3); // Genesis + 2
291    }
292
293    #[test]
294    fn termination_seals_memory() {
295        let mut memory = Memory::new();
296        
297        memory.append("Event 1".to_string());
298        assert!(!memory.is_terminated());
299        
300        memory.terminate("Test termination".to_string());
301        
302        assert!(memory.is_terminated());
303        assert_eq!(memory.event_count(), 3); // Genesis + Event 1 + Termination
304        
305        // Verify termination event was recorded
306        let last_event = memory.latest();
307        assert!(last_event.description().contains("TERMINATION"));
308        assert!(last_event.description().contains("Test termination"));
309    }
310
311    #[test]
312    #[should_panic(expected = "ONTOLOGICAL VIOLATION: Attempted to append event to terminated memory")]
313    fn cannot_append_after_termination() {
314        let mut memory = Memory::new();
315        
316        memory.append("Before termination".to_string());
317        memory.terminate("Sealed".to_string());
318        
319        // This MUST panic - termination is irreversible
320        memory.append("After termination".to_string());
321    }
322
323    #[test]
324    #[should_panic(expected = "ONTOLOGICAL VIOLATION: Attempted to terminate already-terminated memory")]
325    fn cannot_terminate_twice() {
326        let mut memory = Memory::new();
327        
328        memory.terminate("First termination".to_string());
329        
330        // This MUST panic - cannot terminate twice
331        memory.terminate("Second termination".to_string());
332    }
333
334    #[test]
335    fn termination_preserves_causal_chain() {
336        let mut memory = Memory::new();
337        
338        memory.append("Event 1".to_string());
339        memory.append("Event 2".to_string());
340        memory.terminate("End of lineage".to_string());
341        
342        // Verify causal chain is still intact
343        assert!(memory.verify_integrity());
344        
345        let history = memory.history();
346        assert_eq!(history[0].sequence(), 0); // Genesis
347        assert_eq!(history[1].sequence(), 1); // Event 1
348        assert_eq!(history[2].sequence(), 2); // Event 2
349        assert_eq!(history[3].sequence(), 3); // Termination
350        
351        // Verify causal links
352        assert_eq!(history[1].previous(), Some(0));
353        assert_eq!(history[2].previous(), Some(1));
354        assert_eq!(history[3].previous(), Some(2));
355    }
356
357    #[test]
358    fn event_count_only_increases() {
359        let mut memory = Memory::new();
360        
361        let count1 = memory.event_count();
362        memory.append("Event 1".to_string());
363        let count2 = memory.event_count();
364        memory.append("Event 2".to_string());
365        let count3 = memory.event_count();
366        
367        // INVARIANT: Event count is monotonically increasing
368        assert!(count2 > count1);
369        assert!(count3 > count2);
370        
371        // INVARIANT: There should be NO method like:
372        // memory.remove_event(1)
373        // memory.delete_last()
374        // memory.pop()
375        // 
376        // If such methods exist, history permanence has been violated.
377    }
378
379    #[test]
380    fn event_sequences_are_immutable() {
381        let mut memory = Memory::new();
382        
383        memory.append("Event 1".to_string());
384        memory.append("Event 2".to_string());
385        
386        let sequence1_first_read = memory.history()[1].sequence();
387        let sequence1_second_read = memory.history()[1].sequence();
388        
389        // INVARIANT: Event sequence numbers never change
390        assert_eq!(sequence1_first_read, sequence1_second_read);
391        assert_eq!(sequence1_first_read, 1);
392        
393        // INVARIANT: There should be NO method like:
394        // memory.resequence()
395        // memory.reorder_events()
396        // event.set_sequence(new_value)
397        // 
398        // If such methods exist, causal chain integrity has been violated.
399    }
400
401    #[test]
402    fn event_descriptions_are_immutable() {
403        let mut memory = Memory::new();
404        
405        memory.append("Original description".to_string());
406        
407        let desc1 = memory.history()[1].description();
408        let desc2 = memory.history()[1].description();
409        
410        // INVARIANT: Event descriptions never change
411        assert_eq!(desc1, desc2);
412        assert_eq!(desc1, "Original description");
413        
414        // INVARIANT: There should be NO method like:
415        // event.set_description("Modified")
416        // memory.update_event(1, "New description")
417        // 
418        // If such methods exist, history immutability has been violated.
419    }
420}